I am trying to convert a String to LocalDate using DateTimeFormatter, but I receive an exception:
java.time.format.DateTimeParseException: Text '2021-10-31' could not be parsed at index 5
My code is
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-uuuu");
String text = "2021-10-31";
LocalDate date = LocalDate.parse(text, formatter);
I am trying to convert from input date 2021-10-31 to 31-Oct-2021.
Whats wrong?
Your code specifies the pattern
dd-MMM-uuuu, but you attempt to parse the text2021-10-31which does not fit this pattern at all.The correct pattern for your string would be
yyyy-MM-dd. See the documentation of the formatter for details.In particular, watch the order of the days and months
dd-MMMvsMM-dd. And the amount of monthsMMM. A string matching your current pattern would be31-Oct-2021.Change pattern
From the comments:
You can easily change the pattern of the date by:
yyyy-MM-dddd-MMM-yyyy.In code, that is: