菜鸟笔记
提升您的技术认知

Unable to obtain LocalDateTime from TemporalAccessor: {} 错误解决

一、需求描述

想要把  yyyy-MM-dd 格式的字符串,转为 LocalDateTime 对象,代码执行中抛出异常

二、异常记录

Exception in thread "main" java.time.format.DateTimeParseException: Text '2021-10-31' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2021-10-31 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 com.agriculture.util.DateUtil.main(DateUtil.java:22)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2021-10-31 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)
	... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2021-10-31 of type java.time.format.Parsed
	at java.time.LocalTime.from(LocalTime.java:409)
	at java.time.LocalDateTime.from(LocalDateTime.java:457)
	... 4 more

Process finished with exit code 1

三、报错的代码

public static void main(String[] args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime parse = LocalDateTime.parse("2021-10-31", dateTimeFormatter);
        System.out.println(parse);
    }

四、解决方案:yyyy-MM-dd -> LocalDate -> LocalDateTime

代码展示

public static void main(String[] args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime parse = LocalDate.parse("2021-10-31", dateTimeFormatter).atStartOfDay();
        System.out.println(parse);
    }

执行结果

注:以上内容仅提供参考和交流,请勿用于商业用途,如有侵权联系本人删除!