Java日历:为什么UTC偏移被反转?

Kev*_*vin 5 java timezone datetime

我正在努力解决时间问题,我偶然发现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);
}
Run Code Online (Sandbox Code Playgroud)

我可视化算法,用于计算cal以2种形式中的1种表示的时间:

  1. 计算Epoch的毫秒数,添加偏移量(加-4)
  2. 计算(Epoch + offset)的毫秒数.所以从(Epoch - 4 * oneHourMilliseconds)的毫秒数#.

这两种算法都应该产生一个落后4小时的结果utcCal,但运行代码返回4.

可为什么有人向我解释cal,尽管被设置为一个时区4小时背后是的utcCal,最终有4小时后说的毫秒值utcCal?代码不应该返回-4吗?

Jon*_*eet 10

这是一段不幸的历史.ID为"GMT-4"的时区是您期望的 "UTC + 4",即它 UTC 4个小时.

来自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).
Run Code Online (Sandbox Code Playgroud)

这个类似的解释:

如果您可以完全管理它,请避免定义和使用GMT时区......