Java 8 在夏令时结束时创建 ZonedDateTime 实例

Java 8 ZonedDateTime instance creation at the ending of daylight saving

以欧洲芬兰赫尔辛基为例,夏令时将在Sunday, 2017 October 29, 4:00 am结束。

我正在寻找一种方法来创建一个具有正确夏令时设置ZonedDateTime实例(见下文) ,希望通过现有的工厂静态方法。

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

问题:我们如何创建一个 ZonedDateTime 来打印 2017-10-29T03:00+02:00

使用withLaterOffsetAtOverlap()方法:

ZonedDateTime zdt = ZonedDateTime.of(2017, 10, 29, 3, 0, 0, 0,
     ZoneId.of("Europe/Helsinki"));
zdt = zdt.withLaterOffsetAtOverlap();

System.out.println(zdt); // 2017-10-29T03:00+02:00[Europe/Helsinki]

请阅读文档,即ZonedDateTime:

的javadoc

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.

为您的示例显示的代码:

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

输出

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