ZonedDateTimeを文字列にフォーマットする

ZonedDateTimeを文字列にフォーマット

1. 概要

このクイックチュートリアルでは、ZonedDateTimeString.に変換する方法を説明します。

また、String.からZonedDateTimeを解析する方法についても説明します。

2. ZonedDateTimeの作成

まず、UTCのタイムゾーンを持つZonedDateTimeから始めます。 これを実現する方法はいくつかあります。

年、月、日などを指定できます。

ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC"));

現在の日時からZonedDateTimeを作成することもできます。

ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC"));

または、既存のLocalDateTimeからZonedDateTimeを作成できます。

LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));

3. ZonedDateTimeからString

それでは、ZonedDateTimeString.に変換しましょう。このために、we’ll use the DateTimeFormatter class.

タイムゾーンデータを表示するために使用できる特別なフォーマッタがいくつかあります。 フォーマッターの完全なリストはhereにありますが、より一般的なものをいくつか見ていきます。

to display the time zone offset, we can use theフォーマッタ“Z” or “X”が必要な場合:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss Z");
String formattedString = zonedDateTime.format(formatter);

これにより、次のような結果が得られます。

02/01/2018 - 13:45:30 +0000

タイムゾーン名を含めるには、小文字の「z」を使用できます。

DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss z");
String formattedString2 = zonedDateTime.format(formatter2);

この出力は次のようになります。

02/01/2018 - 13:45:30 UTC

4. StringからZonedDateTime

このプロセスは逆にも機能します。 文字列を取得して、ZonedDateTimeに戻すことができます。

これを行う1つのオプションは、static parse() method of the ZonedDateTime class:を使用することです。

ZonedDateTime zonedDateTime = ZonedDateTime.parse("2011-12-03T10:15:30+01:00");

このメソッドは、ISO_ZONED_DATE_TIMEフォーマッターを使用します。 DateTimeFormatterパラメータを受け取るメソッドのオーバーロードバージョンもあります。 ただし、文字列にはゾーン識別子が含まれている必要があります。含まれていないと、例外が発生します。

assertThrows(DateTimeParseException.class, () ->
  ZonedDateTime.parse("2011-12-03T10:15:30", DateTimeFormatter.ISO_DATE_TIME));

StringからZonedDateTimeを取得する2番目のオプションには、2つのステップが含まれます。converting the String to a LocalDateTime, then this object to a ZonedDateTime:

ZoneId timeZone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = LocalDateTime.parse("2011-12-03T10:15:30",
  DateTimeFormatter.ISO_DATE_TIME).atZone(timeZone);

log.info(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));

この間接的な方法は、日付と時刻をゾーンIDと単純に組み合わせます。

INFO: 2011-12-03T10:15:30+02:00[Europe/Athens]

文字列を日付に解析する方法の詳細については、より詳細な日付解析articleを確認してください。

5. 結論

この記事では、ZonedDateTimeを作成する方法と、String.としてフォーマットする方法について説明しました。

また、日時文字列を解析してZonedDateTimeに変換する方法についても簡単に説明しました。

このチュートリアルのソースコードはover on Githubで入手できます。