Search code examples
javalocaldatelocaldatetime

How to parse string (such as "Sunday, July 4, 2021") to LocalDate?


I am trying to parse a string "Sunday, July 4, 2021" to LocalDate as the following:

string this.selectedDate = "Sunday, July 4, 2021";
LocalDate date = LocalDate.parse(this.selectedDate);

But I am getting this error:

java.time.format.DateTimeParseException: Text 'Sunday, July 4, 2021' could not be parsed at index 0

How can I convert such a string full date to the LocalDate?


Solution

  • Try it like this.

    String s = "Sunday, July 4, 2021";
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, LLLL d, yyyy");
    LocalDate ld =  LocalDate.parse(s, dtf);
    System.out.println(ld);
    

    prints

    2021-07-04
    

    Read up on DateTimeFormatter if you want to change the output format.

    Note: If the day of the week is wrong for the numeric day of the month, you will get a parsing error. To avoid this, just skip over or otherwise ignore the day of the week.