DateTimeFormatterのガイド

DateTimeFormatterのガイド

1. 概要

このチュートリアルでは、Java 8DateTimeFormatterクラスとそのフォーマットパターン.を確認します。また、このクラスの考えられる使用例についても説明します。

DateTimeFormatterを使用して、アプリ内の日付と時刻を事前定義またはユーザー定義のパターンで均一にフォーマットできます。

2. 事前定義されたインスタンスを持つDateTimeFormatter

DateTimeFormatter comes with multiple predefined date/time formats はISOおよびRFC標準に準拠しています。 たとえば、ISO_LOCAL_DATEインスタンスを使用して、「2018-03-09」などの日付を解析できます。

DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9));

オフセット付きの日付を解析するには、ISO_OFFSET_DATEを使用して、「2018-03-09-03:00」のような出力を取得できます。

DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")));

Most of the predefined instances of the DateTimeFormatter class are focused on the ISO-8601 standard. ISO-8601は、日付と時刻のフォーマットに関する国際標準です。

ただし、RFC-1123、インターネットホストの要件、IETFによるpublishedを解析する1つの異なる定義済みインスタンスがあります。

DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")));

このスニペットは ‘Fri, 9 Mar 2018 00:00:00 -0300‘を生成します。

既知の形式のStringとして受け取る日付を操作しなければならない場合があります。 parse()メソッドを利用できます。

LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3);

このコードスニペットの結果は、2018年3月12日のLocalDate表現です。

3. DateTimeFormatterFormatStyle

日付を人間が読める方法で印刷したい場合があります。

このような場合、DateTimeFormatterjava.time.format.FormatStyle列挙型(FULL、LONG、MEDIUM、SHORT)値を使用できます。

LocalDate anotherSummerDay = LocalDate.of(2016, 8, 23);
System.out.println(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(anotherSummerDay));
System.out.println(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(anotherSummerDay));
System.out.println(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(anotherSummerDay));
System.out.println(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay));

同じ日付のこれらの異なる書式スタイルの出力は次のとおりです。

Tuesday, August 23, 2016
August 23, 2016
Aug 23, 2016
8/23/16

また、事前定義された書式設定スタイルを日付と時刻に使用する場合があります。 時間とともにFormatStyleを使用するには、ZonedDateTimeインスタンスを使用する必要があります。そうしないと、DateTimeExceptionがスローされます。

LocalDate anotherSummerDay = LocalDate.of(2016, 8, 23);
LocalTime anotherTime = LocalTime.of(13, 12, 45);
ZonedDateTime zonedDateTime = ZonedDateTime.of(anotherSummerDay, anotherTime, ZoneId.of("Europe/Helsinki"));
System.out.println(
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
  .format(zonedDateTime));
System.out.println(
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
  .format(zonedDateTime));
System.out.println(
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
  .format(zonedDateTime));
System.out.println(
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
  .format(zonedDateTime));

今回はDateTimeFormatterofLocalizedDateTime()メソッドを使用したことに注意してください。

そして、得られる出力は次のとおりです。

Tuesday, August 23, 2016 1:12:45 PM EEST
August 23, 2016 1:12:45 PM EEST
Aug 23, 2016 1:12:45 PM
8/23/16 1:12 PM

たとえば、FormatStyleを使用して、日時Stringを解析してZonedDateTimeに変換することもできます。

解析された値を使用して、日付と時刻の変数を操作できます。

ZonedDateTime dateTime = ZonedDateTime.from(
  DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
    .parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
System.out.println(dateTime.plusHours(9));

このスニペットの出力は「2016-08-23T22:12:45 + 03:00 [Europe / Bucharest]」であり、時間が「22:12:45」に変更されていることに注意してください。

4. カスタムフォーマットのDateTimeFormatter

Predefined and built-in formatters and styles can cover a lot of situations。 ただし、日付と時刻を多少異なる形式にする必要がある場合があります。 これは、カスタム書式設定パターンが作用するときです。

4.1. 日付のDateTimeFormatter

31.12.2018のような通常のヨーロッパ形式を使用してjava.time.LocalDateオブジェクトを表示するとします。 これを行うには、ファクトリメソッドDateTimeFormatterofPattern(“dd.MM.yyyy”).を呼び出すことができます。

これにより、日付のフォーマットに使用できる適切なDateTimeFormatterインスタンスが作成されます。

String europeanDatePattern = "dd.MM.yyyy";
DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern);
System.out.println(europeanDateFormatter.format(LocalDate.of(2016, 7, 31)));

このコードスニペットの出力は「31.07.2016」になります。

ニーズに合った日付の形式を作成するために使用できる多くの異なるパターン文字があります。

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10

これは、official Java documentationからDateTimeFormatterクラスへの抽出です。

The number of letters in the pattern format is significant

月に2文字のパターンを使用すると、2桁の月表現が得られます。 月番号が10未満の場合、ゼロが埋め込まれます。 上記のゼロのパディングが必要ない場合は、1月を「1」と表示する1文字のパターン「M」を使用できます。

月に4文字のパターン「MMMM」を使用すると、「完全な形式」の表現が得られます。 この例では、「7月」です。 5文字のパターン「MMMMM」により、フォーマッタは「狭い形式」を使用します。 この場合、「J」が使用されます。

同様に、カスタム書式設定パターンを使用して、日付を保持する文字列を解析することもできます。

DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
System.out.println(LocalDate.from(europeanDateFormatter.parse("15.08.2014")).isLeapYear());

このコードスニペットは、日付「15.08.2014」がうるう年の1つであるかどうかを確認しますが、そうではありません。

4.2. 時間のDateTimeFormatter

時間パターンに使用できるパターン文字もあります。

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978
   n       nano-of-second              number            987654321

DateTimeFormatterを使用してjava.time.LocalTimeインスタンスをフォーマットするのは非常に簡単です。 コロンで区切られた時間(時間、分、秒)を表示するとします。

String timeColonPattern = "HH:mm:ss";
DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern);
LocalTime colonTime = LocalTime.of(17, 35, 50);
System.out.println(timeColonFormatter.format(colonTime));

これにより、出力「17:35:50」が生成されます。

出力にミリ秒を追加する場合は、パターンに「SSS」を追加する必要があります。

String timeColonPattern = "HH:mm:ss SSS";
DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern);
LocalTime colonTime = LocalTime.of(17, 35, 50).plus(329, ChronoUnit.MILLIS);
System.out.println(timeColonFormatter.format(colonTime));

これにより、出力「17:35:50 329」が得られます。

「HH」は、0〜23の出力を生成する時間パターンであることに注意してください。 AM / PMを表示する場合、時間に小文字の「hh」を使用し、「a」パターンを追加する必要があります。

String timeColonPattern = "hh:mm:ss a";
DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern);
LocalTime colonTime = LocalTime.of(17, 35, 50);
System.out.println(timeColonFormatter.format(colonTime));

生成される出力は「05:35:50 PM」です。

カスタムフォーマッタを使用して時間Stringを解析し、正午より前かどうかを確認することをお勧めします。

DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(LocalTime.from(timeFormatter.parse("12:25:30 AM")).isBefore(LocalTime.NOON));

この最後のスニペットの出力は、指定された時間が実際には正午より前であることを示しています。

4.3. タイムゾーンのDateTimeFormatter

Often we want to see a time zone of some specific date-time variable.ニューヨークベースの日時(UTC -4)を使用する場合、タイムゾーン名に「z」パターン文字を使用できます。

String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z";
DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern);
LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15);
System.out.println(newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("UTC-4"))));

これにより、出力「31.07.2016 14:15 UTC-04:00」が生成されます。

前と同じように、タイムゾーンを持つ日付時刻文字列を解析できます。

DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z");
System.out.println(ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15 GMT+02:00")).getOffset().getTotalSeconds());

このコードの出力は、予想どおり「7200」秒、つまり2時間です。

parse()メソッドに正しい日時Stringを指定する必要があります。 最後のコードスニペットのzonedFormatterにタイムゾーンなしで「31.07.201614:15」を渡すと、DateTimeParseExceptionが取得されます。

5. 結論

In this tutorial, we’ve discussed how to use the DateTimeFormatter class for format dates and times.日時インスタンスを操作するときによく発生する実際のサンプルパターンを使用しました。

Java 8Date/Time APIの詳細については、previous tutorialsを参照してください。 いつものように、チュートリアルで使用されるソースコードはover on GitHubで利用できます。