Time Zone
要设置Instant
的格式,需要time-zone.如果没有时区,格式化程序不知道如何将即时时间字段转换为人工日期时间字段,因此会引发异常.
时区可以使用withZone()
直接添加到格式化程序中.
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( Locale.UK )
.withZone( ZoneId.systemDefault() );
如果您特别需要没有显式时区的ISO-8601格式
(如操作员所问),with the time-zone implicitly UTC,你需要
DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))
Generating String
现在使用该格式化程序生成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 );
run 的时候.
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