如何将字符串(如"Sunday, July 4, 2021")解析为LocalDate?

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

我正在尝试将字符串 "Sunday, July 4, 2021" 解析为 LocalDate,如下所示:

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

但是我收到这个错误:

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

如何将这样的字符串完整日期转换为 LocalDate?

像这样尝试。

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

打印

2021-07-04

如果您想更改输出格式,请继续阅读 DateTimeFormatter

注意:如果月份的数字日期是星期几错误,您将得到解析错误。为避免这种情况,请跳过或忽略星期几。