Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Date as of 4 hours ago [duplicate]

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

like image 568
ʞɔıu Avatar asked Dec 03 '10 18:12

ʞɔıu


3 Answers

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();
like image 166
BalusC Avatar answered Dec 26 '22 00:12

BalusC


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.

like image 39
Ole V.V. Avatar answered Dec 26 '22 02:12

Ole V.V.


Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
calendar.getTime();
like image 40
Nicolas Repiquet Avatar answered Dec 26 '22 00:12

Nicolas Repiquet