這是完整的規範:
* Outputs this date-time as a {@code String}, such as
* {@code 2007-12-03T10:15:30+01:00[Europe/Paris]}.
* <p>
* The format consists of the {@code LocalDateTime} followed by the {@code ZoneOffset}.
* If the {@code ZoneId} is not the same as the offset, then the ID is output.
* The output is compatible with ISO-8601 if the offset and ID are the same.
的Javadoc規範指的是ZonedDateTime
被構造成具有ZoneOffset
而非命名ZoneId
的情況下,因此在偏移和ID是相同的:
System.out.println(ZonedDateTime.now(ZoneId.of("Europe/Paris")));
// 2017-04-26T15:13:12.006+02:00[Europe/Paris]
System.out.println(ZonedDateTime.now(ZoneOffset.ofHours(2)));
// 2017-04-26T15:13:12.016+02:00
如可以看到的,在第二種情況下,當使用一個ZoneOffset
,所述toString()
格式省略末尾的括號部分。通過省略該部分,結果是ISO-8601兼容。
boolean iso8601Compatible = zdt.getZone() instanceof ZoneOffset;
爲了保證一個ISO-8601兼容的輸出使用toOffsetDateTime()
:
String isoCompatible = zdt.toOffsetDateTime().toString();
或格式化。
「或格式化程序」:[DateTimeFormatter.ISO_OFFSET_DATE_TIME](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE_TIME)。 –