我有一个要求,我必须将时区从 UTC 转换为特定时区,反之亦然,同时考虑到夏令时。我正在为此使用java.util.TimeZone课程。现在,问题是有数百个时区 ID 无法向用户显示。
作为现在的解决方法,我们决定首先列出国家/地区列表并列出所选国家/地区的时区。我无法获得TimeZoneISO国家代码。
这是我目前用来转换时区的代码,
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());
     }
  });
}