如何将字符串例如“Sunday, July 4, 2021”解析为 LocalDate?

问题描述

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

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

但我收到此错误

java.time.format.DateTimeParseException: Text 'Sunday,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

注意:如果月份中的数字日期是星期几是错误的,则会出现解析错误。为避免这种情况,只需跳过或以其他方式忽略星期几。