gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:52:36 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com