Java 8 – Unable to obtain LocalDateTime from TemporalAccessor

03/19 20:28
阅读数 1.5K

https://mkyong.com/java8/java-8-unable-to-obtain-localdatetime-from-temporalaccessor/


An example of converting a String to LocalDateTime, but it prompts the following errors:

Java8Example.java

package com.mkyong.demo;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Java8Example {

    public static void main(String[] args) {

        String str = "31-Aug-2020";

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);

        LocalDateTime localDateTime = LocalDateTime.parse(str, dtf);

        System.out.println(localDateTime);

    }
}

Output


Exception in thread "main" java.time.format.DateTimeParseException: Text '31-Aug-2020' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
	at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
	at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
	at com.mkyong.demo.Java8Example.main(Java8Example.java:15)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
	at java.base/java.time.LocalDateTime.from(LocalDateTime.java:461)
	at java.base/java.time.format.Parsed.query(Parsed.java:235)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
	... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
	at java.base/java.time.LocalTime.from(LocalTime.java:431)
	at java.base/java.time.LocalDateTime.from(LocalDateTime.java:457)
	... 4 more

Solution

The date 31-Aug-2020 contains no time, to fix it, uses LocalDate.parse(str, dtf).atStartOfDay()


  String str = "31-Aug-2020";

  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);

  LocalDateTime localDateTime = LocalDate.parse(str, dtf).atStartOfDay();

References

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部