2013-11-25 42 views
0

我有一個應用程序,我需要在當地時間顯示事件,而不是位於用戶的時區,但位於事件發生的時區。我以ISO-8601格式獲得時間,包括時區偏移量。時區不是恆定的,我顯示的每個事件可以有不同的(它們代表航班起飛和到達時間)。在GWT中顯示當地時間

例如,我有「2014-02-05T09:00-08:00」,我想將其顯示爲「上午9:00」。

我的第一個,天真的代碼是這樣的:

private static final DateTimeFormat ISO_TIME_FORMAT = 
    DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mmZZZ"); 
private static final DateTimeFormat TIME_OF_DAY_FORMAT = 
    DateTimeFormat.getFormat(PredefinedFormat.HOUR_MINUTE); 

public static String formatTimeOfDay(String iso8601Time) { 
    return TIME_OF_DAY_FORMAT.format(QPX_TIME_FORMAT.parse(iso8601Time)); 
} 

但是,這顯示在用戶時區的時間,在我的情況「上午6:00」,因爲我在美國東部來的。

看看GWT的參考,它看起來像我需要得到基於ISO-8601日期的正確時區,但我不清楚如何做到這一點。我試過

public static String formatTimeOfDay(String isoTime) { 
    Date date = QPX_TIME_FORMAT.parse(isoTime); 
    String tzoneStr = qpxTime.substring(16); 
    TimeZone tzone = TimeZone.createTimeZone(tzoneStr); 
    return TIME_OF_DAY_FORMAT.format(date, tzone); 
} 

但我得到一個「錯誤解析JSON:SyntaxError:意外的數字-05:00」異常。看起來我應該能夠從輸入字符串中解析Date和TimeZone,因爲它包含了編碼的所有信息。

在這一點上,最簡單的事情似乎是直接從輸入時間通過isoTime.substring(11,16)提取時間。這意味着我將不得不編寫一個自定義分析器來從24小時轉換爲am/pm格式,但這可能是最簡單的。

還有其他建議嗎?

回答

0

在GWT 2.5.1 TimeZone.createTimeZone獲取一個JSON版本TimeZoneInfo(這個JSON版本可以在TimeZoneConstants.properties找到)。爲了從「-08:00」區域偏移創建JSON版本,您必須自己解析它。不過,即使有合適的時區仍然沒有工作對我來說:

DateTimeFormat ISO_TIME_FORMAT = DateTimeFormat.getFormat ("yyyy-MM-dd'T'HH:mmZZZ"); 
DateTimeFormat TIME_OF_DAY_FORMAT = DateTimeFormat.getFormat (PredefinedFormat.HOUR_MINUTE); 
String qpxTime = "2014-02-05T09:00-08:00"; 
RootPanel.get().add (new Label ("dts: " + qpxTime)); 
Date dt = ISO_TIME_FORMAT.parse (qpxTime); 
RootPanel.get().add (new Label ("dt: " + dt.toString())); 
String tzs = qpxTime.substring (16); 
RootPanel.get().add (new Label ("tzs: " + tzs)); 
int tzh = Integer.parseInt (qpxTime.substring (16, qpxTime.indexOf (':', 16))); 
RootPanel.get().add (new Label ("tzh: " + tzh)); 
// cf. http://www.docjar.com/html/api/com/google/gwt/i18n/client/TimeZoneInfo.java.html 
// cf. http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/i18n/client/constants/TimeZoneConstants.properties 
TimeZone tz = TimeZone.createTimeZone ("{\"id\": \"fromOffset\", \"std_offset\": " + (tzh * 60) + ", \"transitions\": [], \"names\": \"\"}"); 
RootPanel.get().add (new Label ("tz: " + tz)); 
RootPanel.get().add (new Label ("format plain: " + TIME_OF_DAY_FORMAT.format (dt))); // 9:00 AM 
// cf. http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/i18n/shared/DateTimeFormat.java 
RootPanel.get().add (new Label ("format tz: " + TIME_OF_DAY_FORMAT.format (dt, tz))); // 9:00 AM 
RootPanel.get().add (new Label ("tz offset: " + tz.getStandardOffset())); // 480 
RootPanel.get().add (new Label ("format custom: " + TIME_OF_DAY_FORMAT.format (new Date (dt.getTime() + 60L * 60L * 1000L * tzh)))); // 1:00 PM 

如果你所有的時間包含區域偏移,然後你可以手動將其應用到的時間。但是,如果您也想解析標準區域名稱,則在我看來,您必須解析客戶端上的TimeZoneConstants.properties或將時間轉換卸載到服務器。