0

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"

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Raj
  • 1
  • 1
  • 1
  • You haven’t had much luck with attention to your question. I guess this is because you forgot to add the java tag. I added it for you this time. – Ole V.V. Jan 24 '23 at 11:42
  • You need formatting more than parsing. Use `LocalDate.parse(date)` without the formatter for parsing. Then set `dueDate` to `localDate.format(dateTimeFormatter)`. I got `jan. 25, 02023` in my locale. I recommend you specify which locale you want. You may also use `yyyy` instead of `yyyyy` for 4 digit year. – Ole V.V. Jan 24 '23 at 11:46
  • For the vast majority of purposes you should not convert your date from a string in one format to a string in a different format. You should keep our date in a `LocalDate`. When you receive string input, parse it into a `LocalDate` first thing. Only when you need to give string output, format the `LocalDate` into a new string in the desired format. – Ole V.V. Jan 25 '23 at 07:08

2 Answers2

0

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 );
vincrichaud
  • 2,218
  • 17
  • 34
0

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);
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36