I am getting error as "java.time.format.DateTimeParseException: Text '2023-01-25' could not be parsed at index 0" when passing string "2023-01-25" to parse method.
String date = "2023-01-25";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyyy");
LocalDate localDate = LocalDate.parse(date, dateTimeFormatter);
String dueDate = localDate.toString();
System.out.println(dueDate);
I want to display result as "Jan 25, 2023"
CodePudding user response:
You need 2 different DateTimeFormatter
one to parse your input String into a LocalDate. Then a second to format your LocalDate into the wanted String.
String inputString = "2023-01-25";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(inputString, parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");
String outputString = date.format(formatter);
System.out.println(outputString );
CodePudding user response:
Your format that you created DateTimeFormatter.ofPattern("MMM dd, yyyyy")
is how you want to display your date. Yet you attempt to parse the String "2023-01-25"
to LocalDate
with your format and this obviously fails since your format expects the String to start with 3-letter month name but it starts with "2023". So you need to create 2 formats - one for parsing a String to LocalDate and in your case the pattern should be "yyyy-MM-dd"
. Once you get your LocalDate you can format it to String with your formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyyy");
String outputString = date.format(formatter);