【发布时间】:2020-12-21 16:36:43
【问题描述】:
我尝试使用 DateTimeFormatter 将输入日期解析为 dd/MM/yyyy。我用过下面的代码
java.time.format.DateTimeFormatter 无法解析日期
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withResolverStyle(ResolverStyle.STRICT);
try {
LocalDate.parse(dateField, dateFormatter);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
输入:30/04/2018
Error:Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=4, YearOfEra=2018, DayOfMonth=30},ISO of type java.time.format.Parsed
闰年也是失败的。
【问题讨论】:
-
制作模式
"dd/MM/uuuu"... 或者留下ResolverStyle,但如果你想要ResolverStyle.STRICT,你将不得不使用年份(u)而不是年份(y)。 -
@deHaar — 或使用
DateTimeFormatterBuilder.parseDefaulting()提供默认时代。 -
@OleV.V.那应该作为另一个答案添加...或添加到现有答案之一,但我没有时间了。
-
@deHaar 我想我找到了更适合原始问题的方法。我已经添加并写了a new answer here。
标签: java