0

I keep on getting an error from running this code.

java.time.format.DateTimeParseException: Text 'Jan 03, 2020' could not be parsed at index 0

final String myFormat = "LLL dd, yyyy"; //sets format in which to show date (same as how its saved in database) ex. Jan 29, 2020
final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(myFormat);

String startingBiWeeklyCheck = sharedPreferences.getString("biweekly start", "Jan 03, 2020");
            LocalDate startingDate = LocalDate.parse(startingBiWeeklyCheck, dateFormatter);

Ive played around with the format but I'm not seeing why the pattern "LLL dd, yyyy" doesn't parse Jan 03, 2020

Trevor Soare
  • 120
  • 8

1 Answers1

1

You should use MMM instead of LLL for month parsing.

Updated:

I was wrong about my answer above. It's the half of answer.

The deal is DateTimeFormatter.ofPattern(myFormat) uses default Locale. For non-US locales, it doesn't work. So you need to specify the locale according to your pattern.

DateTimeFormatter.ofPattern(myFormat).withLocale(Locale.US)
Andrei Kovrov
  • 2,087
  • 1
  • 18
  • 28
  • changing the format to "MMM dd, yyyy" is throwing the same exception. – Trevor Soare Nov 12 '20 at 01:40
  • Check your `startingBiWeeklyCheck` variable output. It should always return a string with the same pattern as you specified in `myFormat` – Andrei Kovrov Nov 12 '20 at 01:47
  • By the way, what's your locale? Try also set `DateTimeFormatter.ofPattern(myFormat).withLocale(Locale.US)` – Andrei Kovrov Nov 12 '20 at 01:53
  • @Ole V.V. It's actually interesting because take look the [doc](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) `M/L month-of-year number/text 7; 07; Jul; July; J`. So the L represents number and M represents text value. On my `AdoptOpenJDK 1.8.0_262-b10` it's vise versa! – Andrei Kovrov Nov 13 '20 at 00:07
  • Here is my output https://pastebin.com/MnrFwJrb – Andrei Kovrov Nov 13 '20 at 00:34
  • I've just mentioned that's the question marked as duplicated and https://stackoverflow.com/questions/30518954/datetimeformatter-month-pattern-letter-l-fails has an explanation about this behavior. – Andrei Kovrov Nov 13 '20 at 00:50
  • I admit that the documentation that you quote is easy to misunderstand. `MM` and `LL` are both month number. `MMM` and `LLL` are both month abbreviations, only in a few languages they are different forms. The documentation also says: “**Number/Text:** If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above.” – Ole V.V. Nov 13 '20 at 04:02