我正在尝试使用以下模式解析日期字符串:yyMMdd
和STRICT
解析程序,如下所示:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat).withResolverStyle(ResolverStyle.STRICT);
LocalDate.parse(expiryDate, formatter);
我得到以下DateTimeParseException
:
java.time.format.DateTimeParseException:文本'160501'不能 解析:无法从TemporalAccessor获取LocalDate: {YearOfEra = 2016,MonthOfYear = 5,DayOfMonth = 1},ISO类型 java.time.format.Parsed
当我切换到默认的解析风格时,即ResolverStyle.SMART
,它允许的日期为2月30日。
有人可以帮忙吗?
答案 0 :(得分:8)
严格的解析器需要一个时代与YearOfEra一起使用。将您的模式更改为使用“u”而不是“y”,它将起作用,即。 “uuMMdd”。
答案 1 :(得分:1)
尽管JodaStephen很好地解释了异常的原因并给出了一个好的解决方案(使用uu
而不是yy
),但我提供了其他两种可能的解决方案:
SMART
(默认设置)。换句话说,要么完全忽略.withResolverStyle(ResolverStyle.STRICT)
,要么将其更改为.withResolverStyle(ResolverStyle.SMART)
。对于第二个选项,这里是一个代码示例:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyMMdd")
.parseDefaulting(ChronoField.ERA, 1)
.toFormatter()
.withResolverStyle(ResolverStyle.STRICT);
String expiryDate = "160501";
LocalDate result = LocalDate.parse(expiryDate, formatter);
System.out.println(result);
输出为:
2016-05-01
与在格式模式中使用uu
相比,最后一种解决方案可能会有所不同:
u
或y
。y
时,如果字符串中包含负的年份,则将失败并出现异常。根据您的情况和要求,这可能是理想的还是不可接受的。