我有一个需求,需要将时区从UTC转换到特定的时区,反之亦然,并考虑夏令时。我正在使用
java.util.TimeZone
类来实现。现在的问题是,有几百个时区ID不能显示给用户。
现在我们决定首先列出国家列表,然后根据所选国家列出时区列表作为解决方法。我无法获取ISO国家代码的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));
我需要找出时区ID,以便在上述代码中使用给定的国家ISO代码。
更新:尝试了很多方法,下面的代码可以让我列出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());
}
});
}