我有一个要求,我必须将时区从 UTC 转换为特定时区,反之亦然,同时考虑到夏令时。我正在为此使用 java.util.TimeZone
类。现在,问题是有数百个时区 ID 无法显示给用户。
作为解决方案,我们现在决定首先列出国家/地区列表并列出所选国家/地区的时区。我无法获得 ISO country code 的 TimeZone
.
这是我目前用来转换时区的代码,
Timestamp convertedTime = null;
try{
System.out.println("timezone: "+timeZone +", timestamp: "+timeStamp);
Locale locale = Locale.ENGLISH;
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(destTimeZone);
Date date = new Date(timeStamp.getTime());
System.out.println(formatter.format(date));
convertedTime = new Timestamp(date.getTime());
/*long sixMonths = 150L * 24 * 3600 * 1000;
Date inSixMonths = new Date(timeStamp.getTime() + sixMonths);
System.out.println("After 6 months: "+formatter.format(inSixMonths));
我需要针对给定的国家/地区 ISO 代码找出要在上述代码中使用的时区 ID。
更新:尝试了很多东西,下面的代码让我得到了包含 148 个条目(仍然很大)的时区列表。任何人都可以帮我缩短它。或者,建议一些其他方法来缩短时区列表或获取一个国家/地区的时区,
代码:
public class TimeZones {
private static final String TIMEZONE_ID_PREFIXES =
"^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
private List<TimeZone> timeZones = null;
public List<TimeZone> getTimeZones() {
if (timeZones == null) {
initTimeZones();
}
return timeZones;
}
private void initTimeZones() {
timeZones = new ArrayList<TimeZone>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
if (id.matches(TIMEZONE_ID_PREFIXES)) {
timeZones.add(TimeZone.getTimeZone(id));
}
}
Collections.sort(timeZones, new Comparator<TimeZone>() {
public int compare(final TimeZone a, final TimeZone b) {
return a.getID().compareTo(b.getID());
}
});
}
最佳答案
我认为ICU4J package会帮助你。
关于java - 如何获取指定 ISO 国家代码的时区 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11155929/