【问题标题】:GWT DateTimeFormat reverses timezone valueGWT DateTimeFormat 反转时区值
【发布时间】:2011-07-01 10:06:23
【问题描述】:

考虑以下代码在 GWT 中运行:

import com.google.gwt.i18n.client.DateTimeFormat;
...
DateTimeFormat fullDateTimeFormat = DateTimeFormat.getFullDateTimeFormat();
Log.info(fullDateTimeFormat.format(date, TimeZone.createTimeZone(-120)));
Log.info(fullDateTimeFormat.format(date, TimeZone.createTimeZone(0)));
Log.info(fullDateTimeFormat.format(date, TimeZone.createTimeZone(180))); 

假设现在是格林威治时间 16:00。

为什么我会得到以下输出?

Monday, February 21, 2011 6:00:00 PM Etc/GMT-2
Monday, February 21, 2011 4:00:00 PM Etc/GMT
Monday, February 21, 2011 1:00:00 PM Etc/GMT+3

预期的是

Monday, February 21, 2011 2:00:00 PM Etc/GMT-2
Monday, February 21, 2011 4:00:00 PM Etc/GMT
Monday, February 21, 2011 7:00:00 PM Etc/GMT+3

修复它的正确方法是什么?

【问题讨论】:

    标签: java datetime gwt date timezone


    【解决方案1】:

    “Etc/GMT-2”实际上(并且非常令人惊讶)是“+02:00”,参见http://en.wikipedia.org/wiki/Tz_database#Area:

    为了符合 POSIX 风格,以“Etc/GMT”开头的区域的符号与大多数人的预期相反。在这种样式中,GMT 以西的区域为正号,以东的区域为负号。

    您的代码在我的机器上导致不同的输出(可能是因为我的语言环境不同):

    Monday, 2011 February 21 18:00:00 UTC+2
    Monday, 2011 February 21 16:00:00 UTC
    Monday, 2011 February 21 13:00:00 UTC-3
    

    所以,负责反转的不是DateTimeFormat,而是TimeZone.createTimeZone(int timeZoneOffsetInMinutes)!


    让我们进一步了解 com.google.gwt.i18n.client.TimeZone 的 GWT javadocs:

    getOffset(Date date):

    * Returns the RFC representation of the time zone name for the given date.
    * To be consistent with JDK/Javascript API, west of Greenwich will be
    * positive.
    

    和composeGMTString(int offset):

    * In GMT representation, +/- has reverse sign of time zone offset.
    * when offset == 480, it should output GMT-08:00.
    

    【讨论】:

      【解决方案2】:

      我查看了源代码。它有 cmets 说

      20:00 GMT0000,或 16:00 GMT-0400,或 12:00 GMT-0800

      都是一样的。据我推断,时间和时区之间的关系是从格林威治标准时间减去或添加到格林威治标准时间的时间量。因此 16.00 GMT 变为 1400 GMT -0200 或 1900 GMT +0300。牢记这一点,我们必须反其道而行之,才能获得理想的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-05
        • 2018-03-28
        • 2011-12-22
        • 1970-01-01
        • 2019-11-08
        • 1970-01-01
        • 2011-03-22
        相关资源
        最近更新 更多