Difference between adding Duration.ofDays(1) and Period.ofDays(1) to ZonedDateTime around Daylight Savings Time

Viewed 345

The Daylight Savings Time ends on Nov 1 at 2 AM in US/Eastern time zone. As a result, 2 AM becomes 1 AM.

I am not able to understand the following in the code given below:

  1. Why line 2 shows time 09:00, why not 10:00 (by adding 1 day)?
  2. Why line 4 shows time 10:00, why not 09:00 (by adding 24 hours)?

    LocalDateTime ld = LocalDateTime.of(2015, Month.OCTOBER, 31, 10, 0);
    
    ZonedDateTime date = ZonedDateTime.of(ld, ZoneId.of("US/Eastern"));
    System.out.println(date);       //line 1 - 2015-10-31T10:00-04:00[US/Eastern]
    
    date = date.plus(Duration.ofDays(1));
    System.out.println(date);       //line 2 - 2015-11-01T09:00-05:00[US/Eastern]
    
    date = ZonedDateTime.of(ld, ZoneId.of("US/Eastern"));
    System.out.println(date);       //line 3 - 2015-10-31T10:00-04:00[US/Eastern]
    
    date = date.plus(Period.ofDays(1));
    System.out.println(date);       //line 4 - 2015-11-01T10:00-05:00[US/Eastern]
    

Could somebody please help me with it?

2 Answers

See the full Java documentation on Duration and Period, always one quick Google search away.

From Duration:

In addition, the DAYS unit can be used and is treated as exactly equal to 24 hours, thus ignoring daylight savings effects. See Period for the date-based equivalent to this class.

From Period:

Durations and periods differ in their treatment of daylight savings time when added to ZonedDateTime. A Duration will add an exact number of seconds, thus a duration of one day is always exactly 24 hours. By contrast, a Period will add a conceptual day, trying to maintain the local time

So, Period will maintain the same hour, whereas Duration will add 24 hours.

24 hours after 10:00 on October 31 is 9:00 on November 1st.

  1. 11:00
  2. 12:00
  3. 13:00 (1 pm)
  4. 14:00
  5. 15:00
  6. 16:00
  7. 17:00
  8. 18:00
  9. 19:00
  10. 20:00
  11. 21:00
  12. 22:00
  13. 23:00
  14. 0:00 (midnight)
  15. 1:00
  16. 1:00 (here's that extra hour)
  17. 2:00
  18. 3:00
  19. 4:00
  20. 5:00
  21. 6:00
  22. 7:00
  23. 8:00
  24. 9:00

Duration: Despite the ofDays method Duration hasn’t got a notion of days. Duration.ofDays(1) is immediately converted into 24 hours, so this is what you are adding. Since you add 24 hours to 10:00 the day before DST ends, you get 09:00 the next day as you have observed,

Period: Contrary to Duration a Period knows days, weeks, months and years. So you are adding 1 calendar day, hitting the same wall clock time on the next day (10:00) even though this means 25 hours later (not 24).

Related