Java LocalDateTime解析
作者:互联网
为什么我可以用无效小时解析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,或包括任何毫秒或其他时间组件会导致解析引发错误.
在哪里
LocalDateTime aDate = LocalDateTime.parse("2019-01-01T24:00:00"); //throws an error
抛出错误 – 关于HourOfDay需要在0到23之间 – 正如预期的那样
解决方法:
ResolverStyle
> ResolverStyle.LENIENT
> ResolverStyle.SMART
> ResolverStyle.STRICT
因为如果未指定解析器样式,DateTimeFormatter.ofPattern()默认为ResolverStyle.SMART
. SMART允许一些转换. 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
标签:java,java-time,validation,datetime-parsing 来源: https://codeday.me/bug/20190627/1302804.html