通过时区偏移量获取TimeZone [英] Get TimeZone by timezone offset
问题描述
我需要一个时区,并且有时区偏移.
例如,我的偏移量= 14400000
.我想要一个时区(任何地方,任何城市).我可以在 SimpleDateFormat
中使用该时区,以便为该时区打印正确的时间.
For example, I have offset = 14400000
. I would like to have a timezone (any place, any city). I can use this timezone in SimpleDateFormat
so it prints the correct time for this zone.
这就是我发现的(我重构了一点):
private TimeZone getTimeZone(int offset) {
final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC");
String[] ids = TimeZone.getAvailableIDs(offset);
if (ids == null || ids.length == 0) {
return UTC_TIME_ZONE;
}
String matchingZoneId = ids[0];
return TimeZone.getTimeZone(matchingZoneId);
}
我得到:
sun.util.calendar.ZoneInfo[id="Asia/Baku",offset=14400000,dstSavings=0,useDaylight=false,transitions=68,lastRule=null]
我不喜欢这种方法,因为 TimeZone
将调用此处的 ZoneInfoFile
getZoneIds(int var1)
.这是反编译的代码.
I do not like this approach, because TimeZone
will call ZoneInfoFile
getZoneIds(int var1)
which is here. This is decompiled code.
public static String[] getZoneIds(int var0) {
ArrayList var1 = new ArrayList();
String[] var2 = getZoneIds();
int var3 = var2.length;
for(int var4 = 0; var4 < var3; ++var4) {
String var5 = var2[var4];
ZoneInfo var6 = getZoneInfo(var5);
if (var6.getRawOffset() == var0) {
var1.add(var5);
}
}
var2 = (String[])var1.toArray(new String[var1.size()]);
Arrays.sort(var2);
return var2;
}
您可以看到,它遍历现有对象以构建一个区域ID数组,而我只需要一个!
You can see, that it loops over existing objects to build an array of Zone ids, while I just need one!
我的问题是,有更有效的方法吗?我只需要 ANY 时区ID或给定偏移量的单个时区.
My question, is there a more effective way to do so? I just need ANY timezone id or a single timezone of given offset.
推荐答案
您可以使用
这篇关于通过时区偏移量获取TimeZone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!