Java 将Olson时区ID转换为GWT中的TimeZoneConstant(客户端)

Java 将Olson时区ID转换为GWT中的TimeZoneConstant(客户端),java,gwt,timezone,Java,Gwt,Timezone,我们存储日期是以毫秒为单位存储的,因为我们要显示与时间相关的数据的对象的历元和奥尔森时区ID 如何将Olson TZID转换为TimeZoneConstant以创建时区并使用DateTimeFormat // values from database String tzid = "America/Vancouver"; long date = 1310771967000L; final TimeZoneConstants tzc = GWT.create(TimeZoneConstants.

我们存储日期是以毫秒为单位存储的,因为我们要显示与时间相关的数据的对象的历元和奥尔森时区ID

如何将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); 

这个神奇的函数存在吗?或者有其他方法可以做到这一点吗?

根据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已经存在)。然后我有一个singleton类,它在构造时进行解析:

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调用,将TimeZoneInfo JSON发送到客户端(假设服务器知道我感兴趣的TimeZoneID):

getTimeZone(新的PortalAsyncCallback(){
成功时的公共void(字符串tzJson){
timeZone=timeZone.createTimeZone(TimeZoneInfo.buildTimeZoneData(tzJson));
}
});
这不是最优雅的解决方案,但它为我提供了一种通过DST转换显示特定时区的日期和时间的方法

[1]

这似乎太差劲了?(关于gwt部分,不是我将要复制的您的部分)
getTimeZone(new PortalAsyncCallback<String>() {
  public void onSuccess(String tzJson) {
    timeZone = TimeZone.createTimeZone(TimeZoneInfo.buildTimeZoneData(tzJson));
  }
});