Instant を String にフォーマットするときに UnsupportedTemporalTypeException が発生する 質問する

Instant を String にフォーマットするときに UnsupportedTemporalTypeException が発生する 質問する

新しい Java 8 の日付と時刻 API と次のパターンを使用して、Instant を文字列にフォーマットしようとしています。

Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);

上記のコードを使用すると、サポートされていないフィールドに関する例外が発生します。

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
    at java.time.Instant.getLong(Instant.java:608)
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
    ...

ベストアンサー1

タイムゾーン

フォーマットするにはInstant1つのタイムゾーンが必要です。タイムゾーンがないと、フォーマッタはインスタントを人間の日付/時刻フィールドに変換する方法を知らず、例外をスローします。

タイムゾーンは、次のようにフォーマッタに直接追加できます。withZone()

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

明示的なタイムゾーンのないISO-8601形式(OPが尋ねたように)で、タイムゾーンが暗黙的にUTCである場合、以下が必要です。

DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))

文字列の生成

次に、そのフォーマッタを使用して Instant の文字列表現を生成します。

Instant instant = Instant.now();
String output = formatter.format( instant );

コンソールにダンプします。

System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );

実行すると。

formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34

おすすめ記事