Java LocalDateTime解析

Java LocalDateTime parsing

为什么我可以用无效小时解析 java 中的日期时间字符串?我错过了什么或需要做什么来确保它适当地抛出错误。

下面的代码没有抛出错误,它应该在哪里?

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
LocalDateTime aFormattedDate = LocalDateTime.parse("2019-01-01T24:00:00", dateTimeFormatter); // returns  2019-01-02T00:00:00, should throw an error

将小时指定为 25,或者包括任何毫秒或其他时间部分确实会导致 parse 引发错误。

其中

LocalDateTime aDate = LocalDateTime.parse("2019-01-01T24:00:00"); //throws an error

确实抛出错误 - 关于 HourOfDay 需要介于 0 和 23 之间 - 正如预期的那样

ResolverStyle

因为如果未指定解析器样式,DateTimeFormatter.ofPattern() 默认为 ResolverStyle.SMARTSMART 允许进行一些转换。 24:00:00 将转换为第二天,但 24:00:01 将抛出异常。根据枚举 javadoc:

Style to resolve dates and times in a smart, or intelligent, manner.

Using smart resolution will perform the sensible default for each field, which may be the same as strict, the same as lenient, or a third behavior. Individual fields will interpret this differently.

For example, resolving year-month and day-of-month in the ISO calendar system using smart mode will ensure that the day-of-month is from 1 to 31, converting any value beyond the last valid day-of-month to be the last valid day-of-month.

LocalDateTime.parse() 在后台使用 ResolveStyle.STRICT,这相当于:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss")
                                         .withResolverStyle(ResolverStyle.STRICT);
LocalDateTime.parse("2019-01-01T24:00:00", fmt); // DateTimeParseException