夏時間を考慮して、タイムゾーンを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));
特定の国の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());
}
});
}