gpt4 book ai didi

Java 日历 : Why are UTC offsets being reversed?

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:45 24 4
gpt4 key购买 nike

我正在尝试理解时间处理,但我偶然发现了 Java 中的某些内容,这让我有些困惑。拿这个示例代码:

public static void main(String[] args)
{
//Calendar set to 12:00 AM of the current day (Eastern Daylight Time)
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4"));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
/////

//Calendar set to 12:00 AM of the current day (UTC time)
Calendar utcCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
utcCal.set(Calendar.HOUR_OF_DAY, 0);
utcCal.set(Calendar.MINUTE, 0);
utcCal.set(Calendar.SECOND, 0);
utcCal.set(Calendar.MILLISECOND, 0);
/////

long oneHourMilliseconds = 3600000;
System.out.println((cal.getTimeInMillis() - utcCal.getTimeInMillis()) / oneHourMilliseconds);
}

我将用于计算由 cal 表示的时间的算法可视化为 2 种形式中的一种:

  1. 计算距离Epoch的毫秒数,加上偏移量(add -4)
  2. 从 (Epoch + offset) 计算毫秒数。所以从 (Epoch - 4 * oneHourMilliseconds) 开始的毫秒数。

这两种算法都应产生比 utcCal 晚 4 小时的结果,但是运行代码会返回 4

有人能给我解释一下为什么 cal 尽管被设置为比 utcCal 晚 4 小时 的时区,但最终还是有一个utcCal 后 4 小时的毫秒值?代码不应该返回 -4 吗?

最佳答案

这是一段不幸的历史。 ID 为“GMT-4”的时区是您期望为“UTC+4”的时区,即比 UTC 早 4 小时。 p>

来自 tzdb 的 etcetera 文件:

# We use POSIX-style signs in the Zone names and the output abbreviations,
# even though this is the opposite of what many people expect.
# POSIX has positive signs west of Greenwich, but many people expect
# positive signs east of Greenwich. For example, TZ='Etc/GMT+4' uses
# the abbreviation "GMT+4" and corresponds to 4 hours behind UTC
# (i.e. west of Greenwich) even though many people would expect it to
# mean 4 hours ahead of UTC (i.e. east of Greenwich).

来自this similar explanation :

If you can at all manage it, avoid definitions and use of the GMT timezones...

关于Java 日历 : Why are UTC offsets being reversed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10211805/

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