I am trying to parse dates with the format "27-Sep-2017".
So I tried
String dateStr = "27-Sep-2017";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM-uuuu");
fmt.withLocale(Locale.US);
LocalDate d = LocalDate.parse(dateStr, fmt);
but it throws an exception: DateTimeParseException "Text '27-Sep-2017' could not be parsed at index 3".
It seems to expect Sept not Sep. I had assumed that MMM meant a 3-letter date, which seems to work for the other 11 months.
Is there a format pattern that works for Sep too?
CodePudding user response:
fmt.withLocale(Locale.US);
doesn't set the local date on fmt
. Instead, it returns a new DateTimeFormatter
with that locale. You can either set the locale directly from the ofPattern
method:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.US);
Or, dirtier
String dateStr = "27-Sep-2017";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM-uuuu");
fmt = fmt.withLocale(Locale.US); // NOTICE HERE: reassigning fmt
LocalDate d = LocalDate.parse(dateStr, fmt);