Java夏令时如何确定"lost"小时?
Java How to determine the "lost" hour when changing to summertime?
我想知道 DateTime "2020-03-29 02:15"
是否因时间变化而存在。
我找到了ZoneOffsetTransition
class,里面有一个isGap()
的方法,但是我不明白怎么用
我会简单地转换为 ZonedDateTime
并返回。 ZonedDateTime
坚持选择一个已有的时间,所以如果我们找回相同的时间,那是真的。
ZoneId zone = ZoneId.of("Europe/Berlin");
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
String dateTimeString = "2020-03-29 02:15";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
LocalDateTime check = dateTime.atZone(zone).toLocalDateTime();
if (check.equals(dateTime)) {
System.out.println("This time exists");
} else {
System.out.println("This time does not exist; it is in the spring gap.");
System.out.println("We got " + check);
}
输出为:
This time does not exist; it is in the spring gap.
We got 2020-03-29T03:15
来自 LocalDateTime.atZone()
的文档:
In the case of a gap, where clocks jump forward, there is no valid
offset. Instead, the local date-time is adjusted to be later by the
length of the gap. For a typical one hour daylight savings change, the
local date-time will be moved one hour later into the offset typically
corresponding to "summer".
我想知道 DateTime "2020-03-29 02:15"
是否因时间变化而存在。
我找到了ZoneOffsetTransition
class,里面有一个isGap()
的方法,但是我不明白怎么用
我会简单地转换为 ZonedDateTime
并返回。 ZonedDateTime
坚持选择一个已有的时间,所以如果我们找回相同的时间,那是真的。
ZoneId zone = ZoneId.of("Europe/Berlin");
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
String dateTimeString = "2020-03-29 02:15";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
LocalDateTime check = dateTime.atZone(zone).toLocalDateTime();
if (check.equals(dateTime)) {
System.out.println("This time exists");
} else {
System.out.println("This time does not exist; it is in the spring gap.");
System.out.println("We got " + check);
}
输出为:
This time does not exist; it is in the spring gap. We got 2020-03-29T03:15
来自 LocalDateTime.atZone()
的文档:
In the case of a gap, where clocks jump forward, there is no valid offset. Instead, the local date-time is adjusted to be later by the length of the gap. For a typical one hour daylight savings change, the local date-time will be moved one hour later into the offset typically corresponding to "summer".