Java 8 date-time: get start of day from ZonedDateTime

后端 未结 3 1567
慢半拍i
慢半拍i 2020-12-25 09:34

Is there any difference between these:

zonedDateTime.truncatedTo(ChronoUnit.DAYS);

zonedDateTime.toLocalDate().atStartOfDay(zonedDateTime.getZone());
         


        
3条回答
  •  情话喂你
    2020-12-25 10:07

    They are slightly different. According to the javadocs, truncatedTo() will try to preserve the time zone in the case of overlap, but atStartOfDay() will find the first occurrence of midnight.

    For example, Cuba reverts daylight savings at 1am, falling back to 12am. If you begin with a time after that transition, atStartOfDay() will return the first occurence of 12am, while truncatedTo() will return the second occurence.

    ZonedDateTime zdt = ZonedDateTime.of(2016, 11, 6, 2, 0, 0, 0, ZoneId.of("America/Havana"));
    ZonedDateTime zdt1 = zdt.truncatedTo(ChronoUnit.DAYS);
    ZonedDateTime zdt2 = zdt.toLocalDate().atStartOfDay(zdt.getZone());
    
    System.out.println(zdt);  // 2016-11-06T02:00-05:00[America/Havana]
    System.out.println(zdt1); // 2016-11-06T00:00-05:00[America/Havana]
    System.out.println(zdt2); // 2016-11-06T00:00-04:00[America/Havana]
    

提交回复
热议问题