GWT DateTimeFormat 反转时区值

7

考虑以下代码在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

什么是正确的修复方法?
2个回答

8
"Etc/GMT-2"实际上(非常令人惊讶地)是"+02:00",请参见http://en.wikipedia.org/wiki/Tz_database#Area
为了符合POSIX风格,以"Etc/GMT"开头的时区与大多数人期望的相反。在这种风格中,格林威治时间以西的时区具有正号,以东的时区具有负号。
您的代码在我的机器上导致不同的输出(可能是因为我的Locale不同):
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.

0
我查看了源代码。它有注释说:

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

都是一样的。根据这个,我推断出时间和时区之间的关系是从GMT减去或加上的时间量。因此,16.00 GMT变成了1400 GMT -0200或1900 GMT +0300。记住这一点,我们必须反过来工作才能得到所需的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接