• category: swing folder: TimeZone title: TimeZoneによる日付表示の変換 tags: [DateFormat] author: aterai pubdate: 2004-04-19T10:36:59+09:00 description: TimeZoneなどを使って、日付の表示を変換します。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTVW5Ljb9I/AAAAAAAAAng/mMDH4E_v9ZQ/s800/TimeZone.png

概要

TimeZoneなどを使って、日付の表示を変換します。

サンプルコード

final SimpleDateFormat format =
  new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
final DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("JST"));
//field.setText("Mon, 19 Apr 2004 16:31:41 +0900");
JPanel bp = new JPanel(new GridLayout(1, 0, 2, 2));
bp.add(new JButton(new AbstractAction("format") {
  @Override public void actionPerformed(ActionEvent e) {
    field.setText(format.format(new Date()));
  }
}));
bp.add(new JButton(new AbstractAction("parse") {
  @Override public void actionPerformed(ActionEvent e) {
    String str = field.getText().trim();
    ParsePosition pp = new ParsePosition(0);
    Date date = format.parse(str, pp);
    String o = Objects.nonNull(date) ? df.format(date) : "error";
    textArea.append(o + "\n");
  }
}));
View in GitHub: Java, Kotlin

解説

上記のサンプルは、Locale.US(メールなど)の日付文字列を、SimpleDateFormat#parse(...)メソッドを使用して一旦Dateに変換し、DateFormat#format(...)メソッドでデフォルトロケールTimeZoneのフォーマットスタイルに変換しています。


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

参考リンク

コメント