本文介绍了改变Java日期一小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Java日期对象:
I have a Java date object:
Date currentDate = new Date();
这将给出当前的日期和时间。例如:
This will give the current date and time. Example:
Thu Jan 12 10:17:47 GMT 2012
相反,我想获取日期,将其更改为一个小时,所以应该给我:
Instead, I want to get the date, changing it to one hour back so it should give me:
Thu Jan 12 09:17:47 GMT 2012
什么将是最好的方式吗?
What would be the best way to do it?
推荐答案
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));
这篇关于改变Java日期一小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!