【问题标题】:ZonedDateTime gives incorrect UTC offset valuesZonedDateTime 给出了不正确的 UTC 偏移值
【发布时间】:2017-05-26 21:34:00
【问题描述】:

我正在使用 Java 中的 ZonedDateTime 库从标准时区列表(Olson 时区数据库)中检索任何时区的 UTC 偏移量。

这是我的简单代码。

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class HelloWorld{

    public static void main(String []args){
        displayUtcOffset("Europe/Istanbul");
        displayUtcOffset("America/Caracas");
    }

    public static void displayUtcOffset(String olsonId){
        ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(olsonId));
        float utcOffset = zonedDateTime.getOffset().getTotalSeconds()/3600f;
        System.out.println("For "+olsonId+", UTC"+utcOffset);
    }
}

这些的输出是,

For Europe/Istanbul, UTC2.0
For America/Caracas, UTC-4.5

正如我们所见,加拉加斯的 UTC 偏移量是正确的,但伊斯坦布尔的偏移量实际上是 +3,但它给出的输出是 +2,这是不正确的。 这个 java 库的工作方式是否发生了一些变化?还是有更可靠的库来将 olson Id 转换为 UTC 偏移量?

注:olson Ids List

【问题讨论】:

    标签: java datetime timezone timezone-offset zoneddatetime


    【解决方案1】:

    您是否考虑了夏令时?例如,当你在夏天查看时间时,像这样:

        public static void displayUtcOffset(String olsonId){
            ZonedDateTime zonedDateTime = ZonedDateTime.of(2017, 7, 15, 1, 1, 11, 1, ZoneId.of(olsonId));
            float utcOffset = zonedDateTime.getOffset().getTotalSeconds()/3600f;
            System.out.println("For "+olsonId+", UTC"+utcOffset);
        }
    

    输出与您的预期一致:

    For Europe/Istanbul, UTC3.0
    For America/Caracas, UTC-4.5
    

    【讨论】:

    • 这就是问题所在。即使伊斯坦布尔没有夏令时,这个图书馆仍在考虑它。有没有办法来解决这个问题?还是我需要切换到不同的库?
    • 哦,我不知道土耳其刮掉了夏令时(对他们有好处!)。然后指令已经给here
    【解决方案2】:

    土耳其最近停止遵守 DST,您的时区数据库可能不是最新的。

    the revision history,改动是在tzdata2016g版本中引入的。在撰写本文时,最新版本的 JDK 更新为 111/112 which use tzdata2016f,因此没有正确的土耳其时区。

    您可以等待下一次可能包含更正的 JDK 更新,也可以使用 the Timezone Updater Tool 安装最新的时区数据库。

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多