Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

I am simply trying to convert a date string into a DateTime object in Java 8. Upon running the following lines:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);

I get the following error:

Exception in thread "main" java.time.format.DateTimeParseException: 
Text '20140218' could not be parsed: 
Unable to obtain LocalDateTime from TemporalAccessor: 
{},ISO resolved to 2014-02-18 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)

The syntax is identical to what has been suggested here, yet I am served with an exception. I am using JDK-8u25.

like image 472
retrography Avatar asked Oct 20 '22 11:10

retrography


People also ask

How do I get LocalDateTime in Java 8?

1. LocalDate. LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date.

How do I parse LocalDateTime?

parse(CharSequence text) parse() method of a LocalDateTime class used to get an instance of LocalDateTime from a string such as '2018-10-23T17:19:33' passed as parameter. The string must have a valid date-time and is parsed using DateTimeFormatter. ISO_LOCAL_DATE_TIME.

What is the difference between two LocalDateTime in Java 8?

getDays() + " days " + time[0] + " hours " + time[1] + " minutes " + time[2] + " seconds.");


1 Answers

It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
like image 241
retrography Avatar answered Oct 22 '22 01:10

retrography