Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
john jimenez
3 years ago

this gives the same error