0

I am trying to convert a string date format to another date format(dd-MMM-yyyy) using LocalDate.

String date = "2018-04-16";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);
LocalDate localDate = LocalDate.parse(date, formatter);

I tried this code with and without the Locale.US in the DateTimeFormatter object. Either way it is returning this exception instead:

java.time.format.DateTimeParseException: Text '2018-04-16' could not be parsed at index 2

Is there a way I can handle this date conversion using LocalDate or should I use SimpleDateFormat?

8
  • 2
    Your String date is in yyyy-MM-dd format but the pattern you have specified is dd-MMM-yyyy. Your date would have to be like "16-Apr-2018" for this parse to work. Commented Mar 16, 2023 at 18:47
  • Ok got the problem now. Actually, my concern is to convert the date to the 16-Apr-2018 format. I have 2018-04-16 as my input data. Commented Mar 16, 2023 at 18:50
  • 1
    If your input is yyyy-MM-dd then your DateTimeFormatter needs to use that same pattern to parse it. Then you can output (convert) the resulting LocalDate localDate into any format you want. Commented Mar 16, 2023 at 18:52
  • 1
    Yes, got it to work now. The problem was I directly tried convert the format to the desired format instead of first converting it to LocalDate and then convert. Now I have updated it and it works as you explained. Commented Mar 17, 2023 at 15:52
  • 1
    There were two votes to close this question as not reproducible or caused by a typo. It is perfectly reproducible and not caused by any typo. Instead I have closed it as a duplicate, which I consider both more correct and more helpful. Commented Mar 17, 2023 at 16:25

1 Answer 1

3

In your code DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US); pattern dd-MMM-yyyy is for three letter months like Jun. If you want to parse strings like 2018-04-16, the pattern should be yyyy-MM-dd.

Please refer to the sample code

String date = "2018-04-16";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(date, inputFormatter);

Update - For your question in the comment

After you convert String to Local date, the code below should do the trick.

DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);
String outputDate = localDate.format(outputFormatter);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.