java-8localdate

How to convert date string to localDate when the month is not abbreviated


I am trying to convert the date string that has full month name using LocalDate but I am getting java.time.format.DateTimeParseException: Text could not be parsed at index 6 I tried looking online but can't find suitable solution.

public void iConvertDate() {
        String datevalue = String.valueOf(UIPgAct.dateFormat("10 March 2024", "dd MMM yyyy"));
    }
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public LocalDate dateFormat(String dateToFormat, String fromFormatPattern) {
        LocalDate dateLocal = null;
        if (dateToFormat != null) {
           try {
               DateTimeFormatter dtf = DateTimeFormatter.ofPattern(fromFormatPattern, Locale.US);
               dateLocal = LocalDate.parse(dateToFormat, dtf);
               break;
           } catch (Exception e) {
               System.out.println(e.getMessage());
           }
        }
        return dateLocal;
    }

I tried both "dd MMM yyyy", "dd-MMM-yyyy" formats and both of them returning the same error. I am stuck here. Thanks


Solution

  • If we want to parse full month name like 10 March 2024", We need to use "dd MMMM yyyy" date formatter.

    try with the below LocalDate date= dateFormat("10 March 2024", "dd MMMM yyyy");

    public LocalDate dateFormat(String dateToFormat, String fromFormatPattern) {
            LocalDate dateLocal = null;
            if (dateToFormat != null) {
                try {
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(fromFormatPattern, Locale.US);
                    dateLocal = LocalDate.parse(dateToFormat, dtf);
                    //break;
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            return dateLocal;
        }
    

    this will return Formated Date:2024-03-10