3

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
  • 48,120
  • 14
  • 91
  • 142
hotmeatballsoup
  • 385
  • 6
  • 58
  • 136
  • 2
    Exactly. The whole error message is `Exception in thread "main" java.time.format.DateTimeParseException: Text '20110920' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=9, WeekBasedYear[WeekFields[SUNDAY,1]]=2011, DayOfMonth=20},ISO of type java.time.format.Parsed` The "WeekBasedYear" tips you off that the format is incorrect. The OP wanted "y" but wrote "Y". Probably a common mistake. :) – Ray Toal Sep 20 '18 at 18:17
  • 1
    Same problem as in [Parsing a string to date format in java defaults date to 1 and month to January](https://stackoverflow.com/questions/33427670/parsing-a-string-to-date-format-in-java-defaults-date-to-1-and-month-to-january), though the symptom is not the same. Yes, a common mistake, @RayToal. – Ole V.V. Sep 21 '18 at 07:25

2 Answers2

7

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

No need to specify the format by hand. It’s already built-in.

    final String createdDateStr = "20110920";
    final DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
    final LocalDate localDate = LocalDate.parse(createdDateStr, formatter);
    System.out.println(localDate);

This outputs:

2011-09-20

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161