Java 8 LocalDate won't parse valid date string

hotmeatballsoup :

Java 8 here. I have the following code:

final String createdDateStr = "20110920";
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMdd");
final LocalDate localDate = LocalDate.parse(createdDateStr, formatter);

At runtime I get the following exception:

java.time.format.DateTimeParseException: Text '20110920' could not be parsed at index 0

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.

...being thrown from the LocalDate.parse(...) invocation. What is wrong with the parser?!

Andrew Tobilko :

An example from the documentation:

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);

You should use "yyyyMMdd" instead of "YYYYMMdd". The difference between Y and y was mentioned here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87306&siteId=1