1

現在の日付をアメリカ/モントリオールのタイムゾーンに変換したい。私はこのようにやっています:

Date date = new Date();
TimeZone timeZone = TimeZone.getTimeZone ("America/Montreal");
Calendar cal = new GregorianCalendar(timeZone);
cal.setTime(date);
String whatIWant = "" + cal.get(Calendar.HOUR_OF_DAY) + ':'+ 
                   cal.get(Calendar.MINUTE)+ ':'+ cal.get(Calendar.SECOND);

log.info(whatIWant);

変換は問題ありませんが、このコードはどれほど堅牢か疑問に思いました。夏時間がない場合はどうなりますか?

4

1 に答える 1

6

そのコードは問題ありません。Javaは、冬時間または夏時間を自動的に考慮します。

DateFormatオブジェクトを使用して日付を文字列に変換し、オブジェクトに目的のタイムゾーンを設定することで、これを行うこともできDateFormatます。

Date date = new Date();

DateFormat df = new SimpleDateFormat("HH:mm:ss");

// Tell the DateFormat that you want the time in this timezone
df.setTimeZone(TimeZone.getTimeZone("America/Montreal"));

String whatIWant = df.format(date);
于 2012-06-11T13:43:51.280 に答える