Search code examples
javajava-8dstzoneddatetime

Java 8 ZonedDateTime instance creation at the ending of daylight saving


Take Europe Finland Helsinki as example, the DST will be ended on Sunday, 2017 October 29, 4:00 am.

I'm finding a way to create a ZonedDateTime instance which has the correct DST setting (see below), hopefully through the existing factory static method.

ZonedDateTime beforeDst = ZonedDateTime.of(2017, 10, 29, 3, 59, 0, 0, ZoneId.of("Europe/Helsinki"));
// this will print: 2017-10-29T03:59+03:00[Europe/Helsinki]

beforeDst.plusMinutes(1);
// this will print: 2017-10-29T03:00+02:00[Europe/Helsinki]
// note the +3 become +2, and 3:59 become 3:00

Question: How do we create a ZonedDateTime which will print 2017-10-29T03:00+02:00?

  • hopefully by passing in LocalDateTime as argument or arguments like example above,
  • without plus/remove date operation, and
  • string parsing is not an option (no java.time.format.DateTimeFormatter).

Solution

  • Please read the documentation, i.e. the javadoc of ZonedDateTime:

    For Overlaps, the general strategy is that if the local date-time falls in the middle of an Overlap, then the previous offset will be retained. If there is no previous offset, or the previous offset is invalid, then the earlier offset is used, typically "summer" time.. Two additional methods, withEarlierOffsetAtOverlap() and withLaterOffsetAtOverlap(), help manage the case of an overlap.

    Code to show this for your example:

    ZonedDateTime zdt = ZonedDateTime.of(2017, 10, 29, 3, 00, 0, 0, ZoneId.of("Europe/Helsinki"));
    ZonedDateTime earlier = zdt.withEarlierOffsetAtOverlap();
    ZonedDateTime later = zdt.withLaterOffsetAtOverlap();
    System.out.println(zdt);
    System.out.println(earlier); // unchanged
    System.out.println(later);
    

    Output

    2017-10-29T03:00+03:00[Europe/Helsinki]
    2017-10-29T03:00+03:00[Europe/Helsinki]
    2017-10-29T03:00+02:00[Europe/Helsinki]