我正在使用这个DateTimeFormatter:
DateTimeFormatter.ofPattern("ddMMYY")
我想解析字符串 150790
我收到了这个错误:
Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=15, MonthOfYear=7, WeekBasedYear[WeekFields[MONDAY,4]]=2090},ISO of type java.time.format.Parsed
显然,我希望得到以下内容 TemporalAccessor
:
{DayOfMonth=15, MonthOfYear=7, WeekBasedYear=1990}
你知道我为什么得到2090而不是1990年?
谢谢你的帮助
因为这个问题真的是新的 java.time
- 包装而不是 SimpleDateFormat
我会引用下面的内容 相关部分:
年份:字母数决定了下面的最小字段宽度
使用哪个填充。如果字母数是2,那么减少
使用两位数形式。对于打印,这将输出最右边的两个
数字。对于解析,这将使用2000的基值进行解析,
导致一年在2000至2099年之间。
我们看到Java-8使用了该范围 默认为2000-2099, 不喜欢 SimpleDateFormat
相对于今天而言,相当于+80年的范围。
如果你想配置它,那么你必须使用 appendValueReduced()。这是一个不方便的设计,但可能,请看这里:
String s = "150790";
// old code with base range 2000-2099
DateTimeFormatter dtf1 =
new DateTimeFormatterBuilder().appendPattern("ddMMyy").toFormatter();
System.out.println(dtf1.parse(s)); // 2090-07-15
// improved code with base range 1935-2034
DateTimeFormatter dtf2 =
new DateTimeFormatterBuilder().appendPattern("ddMM")
.appendValueReduced(
ChronoField.YEAR, 2, 2, Year.now().getValue() - 80
).toFormatter();
System.out.println(dtf2.parse(s)); // 1990-07-15
顺便说一下,如果你真的想要以周为基础的年份,那么你必须使用Y代替y或相应的字段 IsoFields.WEEK_BASED_YEAR
。关于您没有任何其他与周相关的字段这一事实,我会假设正常的日历年,而不是基于周的日历年。