Swing/TimeZone のバックアップの現在との差分(No.20)
- category: swing folder: TimeZone title: TimeZoneによる日付表示の変換 tags: [DateFormat] author: aterai pubdate: 2004-04-19T10:36:59+09:00 description: TimeZoneなどを使って、日付の表示を変換します。 image:
概要
TimeZone
などを使って、日付の表示を変換します。
Screenshot
Advertisement
サンプルコード
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
DateFormat df = DateFormat.getDateTimeInstance();
// df.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
df.setTimeZone(TimeZone.getDefault());
JButton formatButton = new JButton("format");
formatButton.addActionListener(e -> field.setText(format.format(new Date())));
JButton parseButton = new JButton("parse");
parseButton.addActionListener(e -> {
String str = field.getText().trim();
Date date = format.parse(str, new ParsePosition(0));
String o = Optional.ofNullable(date).map(df::format).orElse("error");
textArea.append(o + "\n");
});
View in GitHub: Java, Kotlin解説
上記のサンプルは、Locale.US
の日付文字列をSimpleDateFormat#parse(...)
メソッドを使用して一旦Date
に変換し、DateFormat#format(...)
メソッドでデフォルトロケールTimeZone
のフォーマットスタイルに変換しています。
- メモ:
-
dateFormat.setTimeZone(TimeZone.getTimeZone("JST"))
のような3
文字のタイムゾーンID
の使用は非推奨 -
Java 1.7.0
から、タイムゾーンのパターン文字としてX
を使用すると、ISO 8601
形式に変換可能になった-
X
:+09
-
XX
:+0900
-
XXX
:+09:00
-
-
-
dateFormat.setTimeZone(TimeZone.getTimeZone("JST"))
のような3
文字のタイムゾーンID
の使用は非推奨 -
Java 1.7.0
からタイムゾーンのパターン文字X
でISO 8601
形式に変換可能になった-
X
:+09
-
XX
:+0900
-
XXX
:+09:00
-
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
System.out.println("pubdate: " + format.format(new Date()));
// pubdate: 2014-09-08T00:05:45+09:00