Spring Boot 将yyyy-MM-dd格式的文本字符串直接转换为LocalDateTime出现的问题
SpringBoot将yyyy-MM-dd格式的文本字符串直接转换为LocalDateTime出现的问题
问题复现
Exceptioninthread"main"java.time.format.DateTimeParseException:Text'2020-03-12'couldnotbeparsed:UnabletoobtainLocalDateTimefromTemporalAccessor:{},ISOresolvedto2020-03-12oftypejava.time.format.Parsed
atjava.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
atjava.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
atjava.time.LocalDateTime.parse(LocalDateTime.java:492)
atdemo.LocalDateTimeUtils.parseString(LocalDateTimeUtils.java:22)
atdemo.DateTimeDemo.main(DateTimeDemo.java:12)
Causedby:java.time.DateTimeException:UnabletoobtainLocalDateTimefromTemporalAccessor:{},ISOresolvedto2020-03-12oftypejava.time.format.Parsed
atjava.time.LocalDateTime.from(LocalDateTime.java:461)
atjava.time.format.Parsed.query(Parsed.java:226)
atjava.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
...3more
Causedby:java.time.DateTimeException:UnabletoobtainLocalTimefromTemporalAccessor:{},ISOresolvedto2020-03-12oftypejava.time.format.Parsed
atjava.time.LocalTime.from(LocalTime.java:409)
atjava.time.LocalDateTime.from(LocalDateTime.java:457)
...5more
问题解决
解决方案:先将文本字符串日期转化为LocalDate类型,再将LocalDate转化为LocalDateTime
LocalDateTimeUtils.parseStringToLocalDateTime( couponForm.getStartTime(),DateTimeFormatPatternConstants.YYYY_MM_DD)
/** *解析字符串为日期 **说明: *1.该方法主要解决yyyy-MM-dd格式文本字符串无法直接转换为LocalDateTime的问题 * *@paramsource需要解析的日期字符串 *@paramformatPattern日期格式化模式 *@return格式化后的日期 */ publicstaticLocalDateTimeparseStringToLocalDateTime(Stringsource,StringformatPattern){ DateTimeFormatterdateTimeFormatter=DateTimeFormatter.ofPattern(formatPattern); LocalDatelocalDate=LocalDate.parse(source,dateTimeFormatter); returnlocalDate.atStartOfDay(); }
java.time.LocalDate.atStartOfDay()方法将此日期与午夜时间组合在一起,以便在此日期开始时创建LocalDateTime
可参考文档
到此这篇关于SpringBoot将yyyy-MM-dd格式的文本字符串直接转换为LocalDateTime出现的问题的文章就介绍到这了,更多相关SpringBootyyyy-MM-dd转换为LocalDateTime内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。