javajava-timedate-parsing

Parsing LocalDate in Java: What's the pattern for "March 26 2020"


I can't seem to come up with a pattern for "March 26 2020" (no comma). Can someone help? I've tried DateTimeFormatter.ofPattern("MMMM dd yyyy") and DateTimeFormatter.ofPattern("MMM dd yyyy").

Minimal reproducible example:

    String strDate = "March 26 2020";
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM dd uuuu");
    LocalDate date = LocalDate.parse(strDate, dtf);
    System.out.println(date);

On my computer this throws

Exception in thread "main" java.time.format.DateTimeParseException: Text 'March 26 2020' could not be parsed at index 0

Expected output was

2020-03-26

With MMM in the format pattern instead the exception is the same.


Solution

  • Use the pattern, MMMM dd uuuu with Locale.ENGLISH.

    Demo:

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    class Main {
        public static void main(String[] args) {
            String strDate = "March 26 2020";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM dd uuuu", Locale.ENGLISH);
            LocalDate date = LocalDate.parse(strDate, dtf);
            System.out.println(date);
        }
    }
    

    Output:

    2020-03-26