javajava-timedate-parsing

Issue With Converting String to LocalDate


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?


Solution

  • 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);