SpringBoot将
Spring Boot 将yyyy-MM-dd格式的⽂本字符串直接转换为LocalDateTime出现的问题
问题复现
Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-03-12' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-03-12 of type
java.time.format.Parsed
at java.time.ateError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at demo.LocalDateTimeUtils.parseString(LocalDateTimeUtils.java:22)
at demo.DateTimeDemo.main(DateTimeDemo.java:12)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO
resolved to 2020-03-12 of type java.time.format.Parsed
at java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 3 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved
to 2020-03-12 of type java.time.format.Parsed
at java.time.LocalTime.from(LocalTime.java:409)
at java.time.LocalDateTime.from(LocalDateTime.java:457)
... 5 more
问题解决
解决⽅案:先将⽂本字符串⽇期转化为LocalDate类型,再将LocalDate转化为LocalDateTime
LocalDateTimeUtils.parseStringToLocalDateTime(
/**
java时间日期格式转换* 解析字符串为⽇期
* <p>
* 说明:
* 1. 该⽅法主要解决yyyy-MM-dd格式⽂本字符串⽆法直接转换为LocalDateTime的问题
*
* @param source 需要解析的⽇期字符串
* @param formatPattern ⽇期格式化模式
* @return 格式化后的⽇期
*/
public static LocalDateTime parseStringToLocalDateTime(String source, String formatPattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatPattern);
LocalDate localDate = LocalDate.parse(source, dateTimeFormatter);
return localDate.atStartOfDay();
}
java.time.LocalDate.atStartOfDay()⽅法将此⽇期与午夜时间组合在⼀起,以便在此⽇期开始时创建LocalDateTime
到此这篇关于Spring Boot 将yyyy-MM-dd格式的⽂本字符串直接转换为LocalDateTime出现的问题的⽂章就介绍到这了,更多相关SpringBoot yyyy-MM-dd转换为LocalDateTime内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论