gpt4 book ai didi

java - 公历夏令时问题

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:47 29 4
gpt4 key购买 nike

如果我在秋季日光时移结束时(丹麦 2014-10-26 02:00:00 CET)减去一小时(所以我希望回到 02:00 CEST ) 然后将分钟设置为零,我得到了一些奇怪的结果:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("CET"));

cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, Calendar.OCTOBER);
cal.set(Calendar.DAY_OF_MONTH, 26);
cal.set(Calendar.HOUR_OF_DAY, 2);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

System.out.println(cal.getTimeInMillis()); // 1414285200000 : 01:00:00 UTC

cal.add(Calendar.HOUR_OF_DAY, -1);

System.out.println(cal.getTimeInMillis()); // 1414281600000 : 00:00:00 UTC (as expected)

cal.set(Calendar.MINUTE, 0);
// or: cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
// both should be NOPs.

System.out.println(cal.getTimeInMillis()); // 1414285200000 : 01:00:00 UTC (Why?!)

这是一个错误吗?我知道 Java 日历有一些奇怪的约定,但我看不出这怎么可能是正确的。

使用 Calendar 类减去一个小时并将分钟设置为 0 的正确方法是什么?

最佳答案

这是 comments to the similar "bug"来自 Java Bug 跟踪器:

During the "fall-back" period, Calendar doesn't support disambiguation and the given local time is interpreted as standard time.

To avoid the unexpected DST to standard time change, call add() to reset the value.

这意味着您应该将 set() 替换为

cal.add(Calendar.MINUTE, -cal.get(Calendar.MINUTE));

关于java - 公历夏令时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22527872/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com