Ayush Shridhar
Ayush Shridhar

Reputation: 125

Wrong results when adding milliseconds to java.util.date object

Current time is Sat Apr 04 15:02:00 AEST 2020.

In the following snippet, I create a Date object and add 86400000L milliseconds (1 day) to it:

Date date = new Date();
date.setTime(date.getTime() + 86400000L);
System.out.println(date);

The output is Sun Apr 05 14:02:00 AEST 2020. I don't understand why the result adds only 23 hours to my current time, instead of 24 hours.

Any help would be appreciated.

Upvotes: 1

Views: 441

Answers (2)

Anonymous
Anonymous

Reputation: 86324

Do use java.time, the modern Java date and time API, for your date and time work.

    ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("Australia/Sydney"));
    System.out.println(currentTime);
    ZonedDateTime tomorrowSameTime = currentTime.plusDays(1);
    System.out.println(tomorrowSameTime);

Output when running just now:

2020-04-04T16:00:30.579484+11:00[Australia/Sydney]
2020-04-05T16:00:30.579484+10:00[Australia/Sydney]

Please observe: we got the same time of day tomorrow, 16:00. Because summer time (daylight saving time) ends, the UTC offset for tomorrow is different, +10:00 instead of +11:00. And importantly, while I find + 86400000L pretty close to unreadable for adding a day, .plusDays(1) conveys the intention very clearly.

Please insert a different Eastern Australian time zone if required.

What went wrong in your code? cherouvim has explained this very nicely in the other answer, no need for me to repeat. Only allow me to add that the Date class is not only poorly designed — giving rise to your confusion — it is also long outdated. I recommend you don’t use it. And as cherouvim notes in a comment, programming with dates is hard. Don’t trust that you can yourself convert 1 day to 86 400 000 milliseconds. Leave all date and time calculations to proven library methods.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 1

cherouvim
cherouvim

Reputation: 31903

The code works just fine. The AEST on your output means that the date regards Australian Eastern Standard Time. Googling for AEST dst shows that on Sunday, April 5, 3:00 am 2020 the clock will "go back" 1 hour. Thus adding 24 hours just before the DST change, will only move the time 23 hours forward.

If you run that code tomorrow, you'll not have this "problem".

Upvotes: 2

Related Questions