将短日期转换为LocalDate

4

你好,我手头有一个短日期格式,格式为E dd/MM,有没有办法将其转换为LocalDate。

String date = "Thu 07/05";
String formatter = "E dd/MM"; 
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
final LocalDate localDate = LocalDate.parse(date, formatter);`

但它抛出了异常 java.time.format.DateTimeParseException: Text 'Thu 07/05' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=5, DayOfMonth=7, DayOfWeek=4},ISO of type java.time.format.Parsed

我们有没有办法解决这个问题?


3
“年”应该从哪里来? - greg-449
1个回答

3
你只有一个月和一天 - 因此你可以创建一个MonthDay(要创建LocalDate,你还需要年份):
MonthDay md = MonthDay.parse(date, formatter);

如果你想要一个LocalDate,你可以使用MonthDay作为起点:
int year = Year.now().getValue();
LocalDate localDate = md.atYear(year);

或者您可以在格式化程序中使用默认年份:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                        .appendPattern(pattern)
                                        .parseDefaulting(ChronoField.YEAR, year)
                                        .toFormatter(Locale.US);

LocalDate localDate = LocalDate.parse(date, formatter);

这种方法的好处是它还会检查星期几(星期四)是否正确。

1
OP还有一周中的日期,他们可能希望选择的年份与该日期相匹配。 - greg-449

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接