将 Java 日期向后更改一小时

2022-08-31 07:21:22

我有一个 Java 日期对象:

Date currentDate = new Date();

这将给出当前日期和时间。例:

Thu Jan 12 10:17:47 GMT 2012

相反,我想获取日期,将其更改为一小时,以便它应该给我:

Thu Jan 12 09:17:47 GMT 2012

最好的方法是什么?


答案 1

java.util.Calendar

Calendar cal = Calendar.getInstance();
// remove next line if you're always using the current time.
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();

java.util.Date

new Date(System.currentTimeMillis() - 3600 * 1000);

org.joda.time.LocalDateTime

new LocalDateTime().minusHours(1)

Java 8: java.time.LocalDateTime

LocalDateTime.now().minusHours(1)

Java 8 java.time.Instant

// always in UTC if not timezone set
Instant.now().minus(1, ChronoUnit.HOURS));
// with timezone, Europe/Berlin for example
Instant.now()
       .atZone(ZoneId.of("Europe/Berlin"))
       .minusHours(1));

答案 2

类似于@Sumit Jain的解决方案

Date currentDate = new Date(System.currentTimeMillis() - 3600 * 1000);

Date currentDate = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1));