价值24:00
不代表在LocalTime
因为这完全是第二天的一部分。考虑了以下模型:24:00
可以表示为一部分LocalTime
,但结论是,在很多用例中它会非常令人困惑,并且产生的错误比它解决的错误还要多。
有支持24:00
in java.time
然而。完全可以使用标准格式化技术来解析它,但是有必要使用 SMART 或 LENIENT 模式,请参阅旋转变压器风格 http://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html。默认模式是 SMART,但是格式化程序常量DateTimeFormatter
like DateTimeFormatter.ISO_LOCAL_DATE_TIME
处于 STRICT 模式。因此,ofPattern()
默认为 SMART 模式:
static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
LocalDateTime ldt = LocalDateTime.parse("2012-12-03T24:00", FORMATTER);
System.out.println(ldt); // 2012-12-04T00:00
请注意,这也适用于OffsetDateTime
and ZonedDateTime
。标准解析器Instant
支持24:00
没有特殊的格式化程序:
Instant instant = Instant.parse("2015-01-01T24:00:00Z");
System.out.println(instant); // 2015-01-02T00:00:00Z
任何格式化程序都可以使用以下命令转换为 SMART 或 LENIENT 模式withResolverStyle() http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#withResolverStyle-java.time.format.ResolverStyle-如下:
DateTimeFormatter f = ... // obtain a formatter somehow
DateTimeFormatter smartMode = f.withResolverStyle(ResolverStyle.SMART);
// for example
f = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withResolverStyle(ResolverStyle.SMART);
支持的第二个要素是解析多余天数() http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#parsedExcessDays--。这允许在仅解析时间时获得多余的日期:
static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
TemporalAccessor parsed = TIME_FORMATTER.parse("24:00");
LocalTime lt = LocalTime.from(parsed);
Period excessDays = parsed.query(DateTimeFormatter.parsedExcessDays());
System.out.println(lt + " + " + excessDays); // 00:00 + P1D
最后,给高级用户的提示。理论上应该可以编写自己的实现Temporal
这是一个副本LocalTime
但有支持24:00
作为有效值。这样的班级,说LocalTimeWithEndOfDay
,然后可以毫无问题地使用格式化程序/解析器(并且可能是一个很好的补充三十额外 http://www.threeten.org/threeten-extra/.