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
- DateTimeFormatter JavaDoc
- LocalDateTime JavaDoc
- Java 8 – How to parse date with LocalDateTime
- Java 8 – How to convert String to LocalDate