Java 将 X 小时添加到日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23554801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:52:11  来源:igfitidea点击:

Add X hours to a date & time

javadatetimecalendarforward

提问by user2911924

I am currently fetching the time and date trough:

我目前正在获取时间和日期低谷:

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

This returns the example '05/14/2014 01:10:00'

这将返回示例 '05/14/2014 01:10:00'

Now I am trying to make it so I can add a hour to this time without having to worry about a new day or month etc.

现在我正在努力做到这一点,这样我就可以在这个时间上增加一个小时,而不必担心新的一天或一个月等。

How would I go on getting '05/14/2014 01:10:00' but then for 10 hours later in the same format?

我将如何继续获得 '05/14/2014 01:10:00' 但在 10 小时后以相同的格式?

Thanks in advance.

提前致谢。

采纳答案by Robert Durgin

Look at the Calendar object: Calendar

查看 Calendar 对象: Calendar

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 10);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println(dateFormat.format(cal.getTime()));

回答by mrres1

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

/*
 * Add x hours to the time
 */

int x = 10;

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

calendar.add(Calendar.HOUR, x);

System.out.println(dateFormat.format(calendar.getTime()));

Console output:

控制台输出:

05/08/2014 20:34:18
05/09/2014 06:34:18

回答by VGR

As others have mentioned, the Calendar class is designed for this.

正如其他人所提到的,Calendar 类就是为此而设计的。

As of Java 8, you can also do this:

从 Java 8 开始,您还可以这样做:

DateTimeFormatter dateFormat =
    DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

LocalDateTime date = LocalDateTime.now();
System.out.println(dateFormat.format(date));
System.out.println(dateFormat.format(date.plusHours(10)));

java.time.format.DateTimeFormatteruses a lot of the same pattern letters as java.text.SimpleDateFormat, but they are not all the same. See the DateTimeFormatter javadocfor the details.

java.time.format.DateTimeFormatter使用许多与 相同的模式字母java.text.SimpleDateFormat,但它们并不完全相同。有关详细信息,请参阅DateTimeFormatter javadoc

回答by Ashish John

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = new Date();
final long reqHoursInMillis = 1 * 60 * 60 * 1000;  // change 1 with required hour
Date newDate = new Date(currentDate.getTime() + reqHoursInMillis);
System.out.println(dateFormat.format(newDate));

This will add 1 hour in current time in the given date format. Hope it helps.

这将以给定的日期格式在当前时间增加 1 小时。希望能帮助到你。