开发者

Get Date as of 4 hours ago [duplicate]

This question already has answers here: How to create a Date object, using UTC, at a specific time in the past? 开发者_如何学JAVA (2 answers) Closed 4 years ago.

How can I return a Date object of 4 hours less than the current system time in Java?


If you're already on Java 8 or newer:

LocalDateTime fourHoursAgo = LocalDateTime.now().minusHours(4);

Or if you want to take DST (Daylight Saving Time) into account (just in case it coincidentally went into or out DST somewhere the last 4 hours):

ZonedDateTime fourHoursAgo = ZonedDateTime.now().minusHours(4);

Or if you're not on Java 8 yet:

Date fourHoursAgo = new Date(System.currentTimeMillis() - (4 * 60 * 60 * 1000));

And you want to take DST into account:

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
Date fourHoursAgo = calendar.getTime();


The other answers are correct, but I would like to contribute the modern answer. The modern solution uses java.time, the modern Java date and time API.

Instant fourHoursAgo = Instant.now().minus(Duration.ofHours(4));
System.out.println(fourHoursAgo);

This just printed:

2018-01-31T15:22:21.113710Z

The Z in the end indicates that the time is printed in UTC — at UTC offset zero if you will. The Instant class is the modern replacement for Date, so I recommend you stick to it. The modern API is generally so much nicer to work with, so much cleaner, so much better designed.

Please note the advantages of letting the library class do the subtraction of 4 hours for you: the code is clearer to read and less error-prone. No funny constants, and no readers taking time to check if they are correct.

If you do need an old-fashioned Date object, for example when using a legacy API that you cannot change or don’t want to change, convert like this:

Date oldfashionedDate = Date.from(fourHoursAgo);

Link: Oracle Tutorial trail: Date Time. Of course there are other resources on the internet too, please search.


Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
calendar.getTime();


Convert it to milliseconds, subtract the number of milliseconds in 4 hours, convert it back to a Date.


Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR_OF_DAY, -4);
java.util.Date d = c.getTime();
System.out.println(d);


Calendar c =Calendar.getInstance() ;
c.add(Calendar.HOUR,-4);
Date d = c.getTime();


Use a Calendar object and the add method.

calendar.add(Calendar.HOUR, -4);

See http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜