2011-12-15 36 views
4

我們存儲的日期存儲的時間以毫秒爲單位,並且Olson時區ID用於顯示與時間相關的數據對象的對象。在GWT(客戶端)中將Olson時區ID轉換爲TimeZoneConstant

如何將Olson TZID轉換爲TimeZoneConstant以創建時區並使用DateTimeFormat?

// values from database 
String tzid = "America/Vancouver"; 
long date = 1310771967000L; 


final TimeZoneConstants tzc = GWT.create(TimeZoneConstants.class); 
String tzInfoJSON = MAGIC_FUNCTION(tzid, tzc); 
TimeZone tz = TimeZone.createTimeZone(TimeZoneInfo.buildTimeZoneData(tzInfoJSON)); 
String toDisplay = DateTimeFormat.getFormat("y/M/d h:m:s a v").format(new Date(date), tz); 

MAGIC_FUNCTION是否存在?還是有另一種方法來做到這一點?

回答

4

根據GWT Javadoc [1],在TimeZoneConstants類上做一個GWT.create是一個糟糕的遊戲。所以我所做的是在服務器端創建一個類,用於解析/com/google/gwt/i18n/client/constants/TimeZoneConstants.properties併爲每個時區構建一個所有JSON對象的緩存(由其Olson TZID索引) )。

我的網站在jboss上運行,所以我將TimeZoneConstants.properties複製到我的網站的war/WEB-INF/lib目錄中(可能不需要在那裏複製它,因爲GWT jar已經存在)。然後,我有一個單例類構造的時候,做了解析:

InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILE); 
InputStreamReader isr = new InputStreamReader(inStream); 
BufferedReader br = new BufferedReader(isr); 
for (String s; (s = br.readLine()) != null;) { 
    // using a regex to grab the id to use as a key to the hashmap 
    // a full json parser here would be overkill 
    Pattern pattern = Pattern.compile("^[A-Za-z]+ = (.*\"id\": \"([A-Za-z_/]+)\".*)$"); 
    Matcher matcher = pattern.matcher(s);  
    if (matcher.matches()) { 
    String id = matcher.group(2); 
    String json = matcher.group(1); 

    if (!jsonMap.containsKey(id)) { 
     jsonMap.put(id, json); 
    } 
    } 
} 
br.close(); 
isr.close(); 
inStream.close(); 

最後我做一個RPC調用來獲取TimeZoneInfoJSON客戶端(假設服務器知道哪些TimeZoneID我感興趣的):

getTimeZone(new PortalAsyncCallback<String>() { 
    public void onSuccess(String tzJson) { 
    timeZone = TimeZone.createTimeZone(TimeZoneInfo.buildTimeZoneData(tzJson)); 
    } 
}); 

不是最優雅的解決方案,但它給了我一種顯示日期和時間的方式來顯示DST轉換的特定時區。

[1] http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/i18n/client/constants/TimeZoneConstants.html

+0

這看起來很蹩腳? (在gwt部分,不是我將要複製的你的) – NimChimpsky 2017-03-07 23:40:25