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

skip :

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?

Ole V.V. :

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).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113310&siteId=1