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
.
What Am I doing wrong in my code.
Your code specifies the pattern dd-MMM-uuuu
, but you attempt to parse the text 2021-10-31
which 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-MMM
vs MM-dd
. And the amount of months MMM
. A string matching your current pattern would be 31-Oct-2021
.
From the comments:
my input date is - 2021-10-31 need to covert into - 31-Oct-2021
You can easily change the pattern of the date by:
yyyy-MM-dd
dd-MMM-yyyy
.In code, that is:
DateTimeFormatter inputPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter outputPattern = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String input = "2021-10-31";
LocalDate date = LocalDate.parse(text, inputPattern);
String output = date.format(outputPattern);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With