这是完整的规范:
* 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)。 –