Java LocalDateTime解析
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java LocalDateTime解析,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1594字,纯文字阅读大概需要3分钟。
内容图文
![Java LocalDateTime解析](/upload/InfoBanner/zyjiaocheng/790/20bfcffa7a5b449c81914ef3b157c45c.jpg)
为什么我可以用无效小时解析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 LocalDateTime解析全部内容,希望文章能够帮你解决Java LocalDateTime解析所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。