タイムゾーン
タイムゾーンをフォーマットするInstant
には必須です。タイムゾーンがないと、フォーマッタはインスタントを人間の日付/時間フィールドに変換する方法がわからないため、例外がスローされます。
を使用して、タイムゾーンをフォーマッタに直接追加できます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