为什么 ZonedDateTime 和日历在 2050 年的小时上存在分歧?



请考虑以下代码:

ZoneId zoneId = ZoneId.of("America/Los_Angeles");
long currMillis = 2530778400000L;
Instant curr = Instant.ofEpochMilli(currMillis);
LocalDateTime dt = LocalDateTime.ofInstant(curr, zoneId); //the local one just for completeness
ZonedDateTime zdt = ZonedDateTime.ofInstant(curr, zoneId);
Calendar calendar = GregorianCalendar.from(zdt);
System.out.println(String.format("%-30s %s", "java-8 LocalDateTime hour:", dt.toLocalTime().getHour()));
System.out.println(String.format("%-30s %s", "java-8 ZonedDateTime hour:", zdt.toLocalTime().getHour()));
System.out.println(String.format("%-30s %s", "Calendar hour:", calendar.get(Calendar.HOUR_OF_DAY)));

印刷:

java-8 LocalDateTime hour:     3
java-8 ZonedDateTime hour:     3
Calendar hour:                 2

似乎在这个小时左右,日历从第 2 小时跳到第 4 小时(如果它对应于 DST 更改,则通常不一定是问题(。

我正在使用AdoptOpenJDK 1.8.0_242,但我也检查了HotSpot 1.8.0_181 - 同样的问题。

为什么"日历"报告的小时数与"分区日期时间"不同?
这种不匹配是已知问题吗?
在这种情况下,我应该更信任谁 - ZonedDateTime 或 Calendar?

假设规则(过渡到 DST 发生在 3 月 8 日或之后的第一个星期日的 02:00(在 2050 年没有改变,那么这个时刻就是发生间隙过渡的时刻(3 月 13 日(,时钟从 01:59 跳到 03:00,所以 02:00 实际上并不存在。Calendar在这里是完全错误的。

您可以通过检查每个时区类对相关时刻的描述来进一步了解Calendar的错误程度。ZonedDateTime使用ZoneId,而Calendar使用TimeZone。我使用以下代码将ZoneId上各种方法的输出与TimeZone对应方法的输出进行了比较:

ZoneId zoneId = ZoneId.of("America/Los_Angeles");
long currMillis = 2530778400000L;
Instant curr = Instant.ofEpochMilli(currMillis);
TimeZone tz = TimeZone.getTimeZone(zoneId);
// what's the actual offset at that instant?
System.out.println(zoneId.getRules().getOffset(curr).getTotalSeconds());
System.out.println(tz.getOffset(currMillis) / 1000);
// is DST observed at that instant?
System.out.println(zoneId.getRules().isDaylightSavings(curr));
System.out.println(tz.inDaylightTime(new Date(currMillis)));
// what's the standard offset at that instant?      
System.out.println(zoneId.getRules().getStandardOffset(curr).getTotalSeconds());
System.out.println(tz.getRawOffset() / 1000);
// how many seconds does DST add to the standard offset at that instant?
System.out.println(zoneId.getRules().getDaylightSavings(curr).getSeconds());
Calendar calendar = GregorianCalendar.from(ZonedDateTime.ofInstant(curr, zoneId));
System.out.println(calendar.get(Calendar.DST_OFFSET) / 1000);

结果如下:

-25200
-28800
true
true
-28800
-28800
3600
0

如您所见,他们都认为观察到了 DST,但TimeZone认为 DST 在标准偏移量上增加了 0 秒,这使得它认为实际偏移量仍然是 -8 小时。

但谁知道30年后会发生什么?让我们希望每个人都摆脱夏令时:)

相关内容

最新更新