【问题标题】:Java time zone with DST prints incorrect time (in negative epochs)带有 DST 的 Java 时区打印不正确的时间(在负数时期)
【发布时间】:2016-04-05 12:23:57
【问题描述】:

我很难理解以下代码的行为:

    TimeZone zone = TimeZone.getTimeZone("Asia/Jerusalem");
    DateFormat format = DateFormat.getDateTimeInstance();
    format.setTimeZone(zone);

    //printing out 4 different epoch dates

    //print out using formatter with TZ
    System.out.println(format.format(new Date(-1712458800000L))); 
    //print using Date's toString method
    System.out.println(new Date(-1712458800000L)); 

    System.out.println(format.format(new Date(-57844760000L)));
    System.out.println(new Date(-57844760000L));

    System.out.println(format.format(new Date(-1888228760000L)));
    System.out.println(new Date(-1888228760000L));

    System.out.println(format.format(new Date(1456920000000L)));
    System.out.println(new Date(1456920000000L));

在我的本地机器(时区 GMT+2 耶路撒冷)上运行时,在 Windows 中选中“自动调整 DST 时钟”(这使我成为 GMT+3) 它产生以下输出:

Sep 26, 1915 11:20:40 PM
Sun Sep 26 23:20:40 IST 1915

Mar 2, 1968 2:00:40 PM
Sat Mar 02 14:00:40 IST 1968

Mar 2, 1910 2:21:20 PM
Wed Mar 02 14:21:20 IST 1910

Mar 2, 2016 2:00:00 PM
Wed Mar 02 14:00:00 IST 2016

但是当我取消选中它时(这使我成为 GMT+2),运行相同的代码会产生

Sep 26, 1915 11:20:40 PM
Sun Sep 26 23:00:00 GMT+02:00 1915

Mar 2, 1968 2:00:40 PM
Sat Mar 02 14:00:40 GMT+02:00 1968

Mar 2, 1910 2:21:20 PM
Wed Mar 02 14:00:40 GMT+02:00 1910

Mar 2, 2016 2:00:00 PM
Wed Mar 02 14:00:00 GMT+02:00 2016

第一个示例和第三个示例在使用 Date 的 toString() 时的分钟和秒不同。 如您所见,当我使用 DateFormat 明确设置 TZ 时,它会打印出相同的结果。 我在这里错过了什么?

谢谢!

【问题讨论】:

  • 问题可能是您正在根据历史上(在 1910 年代)对 GMT 有不同偏移量的时区打印时间。
  • 您可以在这里查看timeanddate.com/time/zone/israel/jerusalem 并选择Time zone changes for 1900-1924 期间。在那里,您可以看到所有年份的偏移量都不相同。但我不知道是什么原因造成的变化,在互联网上快速搜索时找不到。

标签: java timezone timezone-offset


【解决方案1】:

让我们看看你 1915 年的例子。值 -1712458800000 作为 millis-since-the-unix-epoch 是 1915-09-26T21:00:00Z - 换句话说,正好是世界标准时间晚上 9 点。

现在回到 1915 年,耶路撒冷的 UTC 偏移量是 +2:20:40,这就是为什么您会在输出的第一行看到“Sep 26, 1915 11:20:40 PM”。但是,当您在 Windows 中关闭 DST 时,Windows 或 Java 都将其视为“将其视为 UTC+2 的固定时区”。这并不是真正的“在没有 DST 更改的情况下将其视为耶路撒冷,而是在进行其他更改”。因此,您会在第二行中看到 UTC+2 的值,即“Sun Sep 26 23:00:00 GMT+02:00 1915”。

基本上,“没有 DST 的这个时区”的概念是一个非常奇怪的概念,并且已被简化(再次,我不确定是 Windows 还是 Java),只是一个固定的偏移量。当“标准”偏移量没有改变时这很好,但是当它改变时会导致这样的问题。在合理的现代历史中,大多数时区都没有改变其标准偏移量,但在 20 世纪初发生了相当多的变化。

【讨论】:

  • 谢谢大家。让我感到困惑的是,我不知道历史上的时区之间可能会相差小时和分钟(+2:20:40)
  • @shays10 可以相差几秒。
猜你喜欢
  • 1970-01-01
  • 2013-03-13
  • 2011-07-06
  • 2011-01-06
  • 2015-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多