開発者ドキュメント

DateTimeFormatterのガイド

1.概要

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


DateTimeFormatter

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

2.定義済みインスタンスを含む

DateTimeFormatter

  • **

    DateTimeFormatter

    には、ISOおよびRFC標準に準拠した複数のhttps://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO

    LOCAL

    DATE[事前定義された日付/時刻フォーマット]が付属しています。 。たとえば、

    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")));
  • __DateTimeFormatterクラスの定義済みインスタンスの大部分は、ISO-8601標準に焦点を当てています** ISO-8601は、日付と時刻のフォーマットに関する国際標準です。

ただし、IETFによるRFC-1123、インターネットホストの要件、https://tools.ietf.org/html/rfc1123.html[公開]を解析する、定義済みのインスタンスが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.

FormatStyle

を含む

DateTimeFormatter

時々私達は人間が読める方法で日付を印刷したいかもしれません。

そのような場合、

DateTimeFormatter

と共に

java.time.format.FormatStyle

enum(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));

今回は

DateTimeFormatterの

ofLocalizedDateTime()メソッドを使用しました。

そして私達が得る出力は次のとおりです。

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[ヨーロッパ/ブカレスト]」です。時刻が「22:12:45」に変更されたことに注意してください。

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

DateTimeFormatter

  • 定義済みのビルトインフォーマッタとスタイルは多くの状況をカバーできます。しかし、時々私達は幾分異なった日時をフォーマットする必要があります。これがカスタムフォーマットパターンが登場するときです。

4.1. 日付の

DateTimeFormatter

31.12.2018のような通常のヨーロッパ形式を使用して

java.time.LocalDate

オブジェクトを提示したいとします。これを行うには、ファクトリメソッド

DateTimeFormatter

.__ ofPattern(“ 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

これはhttps://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html[公式のJavaドキュメント]を

DateTimeFormatter

クラスに展開したものです。

  • パターンフォーマットの文字数は重要です** 。

月に2文字のパターンを使用すると、2桁の月の表現が得られます。月数が10より小さい場合は、ゼロが埋め込まれます。前述の0で埋め込む必要がない場合は、1文字のパターン「M」を使用できます。これは1月を「1」と表示します。

月に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

」がうるう年かどうかを確認します。

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

  • 特定の日時変数のタイムゾーンを見たいことがよくあります** ニューヨークを基準にした日時(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.2016 14:15”を渡すと、

DateTimeParseException

が返されます。

5.まとめ

  • このチュートリアルでは、日付と時刻のフォーマットに

    __DateTimeFormatter

    __classを使用する方法について説明しました。

Java 8 __ Date/Time APIの詳細については、https://www.baeldung.com/java-8-date-time-intro[以前のチュートリアル]を参照してください。いつものように、チュートリアルで使用されているソースコードはhttps://github.com/eugenp/tutorials/tree/master/java-dates[GitHubで利用可能]です。

モバイルバージョンを終了