在 Java 中为日期添加 n 小时? [英] Adding n hours to a date in Java?

查看:15
本文介绍了在 Java 中为日期添加 n 小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向 Date 对象添加 n 小时?我在 StackOverflow 上找到了另一个使用 days 的示例,但仍然不明白如何使用 hours 来完成.

How do I add n hours to a Date object? I found another example using days on StackOverflow, but still don't understand how to do it with hours.

推荐答案

检查 Calendar 类.它有 add 方法(和其他一些方法)来允许时间操作.

Check Calendar class. It has add method (and some others) to allow time manipulation.

这样的事情应该可以工作:

Something like this should work:

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date());               // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1);      // adds one hour
cal.getTime();                         // returns new date object plus one hour

查看 API 了解更多信息.

Check API for more.

这篇关于在 Java 中为日期添加 n 小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆