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

标签 java gwt timezone

我们存储我们的日期以毫秒为单位存储,因为我们想要显示时间相关数据的对象的纪元和奥尔森时区 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); 

那个 MAGIC_FUNCTION 存在吗?或者还有其他方法吗?

最佳答案

根据 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

关于java - 将 Olson 时区 ID 转换为 GWT 中的 TimeZoneConstant(客户端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8528173/

相关文章:

Java:计算时区差异

javascript - 使用 Moment.js 清理时间的最佳方法是什么?

java - 从时区对象返回错误的夏令时偏移

java - 如何通过移动网络浏览器运行Android应用程序(渐进式应用程序)

java - Android-sqlite 全部删除

eclipse - 在 Eclipse 中使用 GWT + Maven 项目

java - 链表 - 在当前节点之前插入一个节点

google-app-engine - Eclipse Juno 4.2 Google 插件未安装 : Cannot complete install because one or more required items could not be found

gwt - 在 GWT 中使用查询字符串

javascript - 从 HTML 日期选择器 : incorrect date returned 初始化 JS 日期对象