【问题标题】:Java set DateFormat timezone to GMT+1Java 将 DateFormat 时区设置为 GMT+1
【发布时间】:2013-02-18 15:57:47
【问题描述】:

将 DateFormat 时区设置为 GMT+1 的正确字符串是什么? 根据文档,它应该类似于“GMT + 00:00”。 我已经尝试过其他形式,但显然我总是回退到 GMT(我当前的时区)。

提前致谢!

【问题讨论】:

    标签: java timezone simpledateformat


    【解决方案1】:

    你可以使用

    TimeZone fixedUtcPlus1 = new SimpleTimeZone(TimeUnit.HOURS.toMillis(1),
                                                "GMT+1");
    format.setTimeZone(fixedUtcPlus1);
    

    或者只是:

    TimeZone zone = TimeZone.getTimeZone("GMT+1");
    format.setTimeZone(zone);
    

    (对围绕 +1 和 -1 的重复编辑表示歉意……我的诊断错误。“GMT+1”很好,但它的 Etc 等价物是“Etc/GMT-1” - 非常令人困惑。)

    【讨论】:

    • SimpleTimeZone 构造函数只接受一个 int,而不是一个 long,所以我会说 new SimpleTimeZone((int) TimeUnit.HOURS.toMillis(1), "GMT+1");会更正确。 ...感谢 Etc/GMT-1 实际上是 GMT+1 的解释。那些奇怪的东西让我怀疑我这几天是不是自己做错了什么! :)
    【解决方案2】:

    您可以通过以下代码片段找到整套时区:

    for (String id : TimeZone.getAvailableIDs()) {
        System.out.println(id);
    }
    

    并重用它直接设置时区:

    DateFormat df = DateFormat.getDateInstance();
    df.setTimeZone(TimeZone.getTimeZone(id));
    

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2022-01-21
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      相关资源
      最近更新 更多