欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Spring Boot 将yyyy-MM-dd格式的文本字符串直接转换为LocalDateTime出现的问题

时间:2021-05-06 09:39:47|栏目:JAVA代码|点击:

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.format.DateTimeFormatter.createError(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(
    couponForm.getStartTime(), DateTimeFormatPatternConstants.YYYY_MM_DD)
/**
 * 解析字符串为日期
 * <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

可参考文档

上一篇:详解Android中的Toast源码

栏    目:JAVA代码

下一篇:SpringMvc+POI处理excel表数据导入

本文标题:Spring Boot 将yyyy-MM-dd格式的文本字符串直接转换为LocalDateTime出现的问题

本文地址:http://www.codeinn.net/misctech/115648.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有