我正在使用这个 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
-package 而不是 SimpleDateFormat
我将引用以下 relevant section :
Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a reduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
我们看到 Java-8 默认使用 2000-2099 范围,不像 SimpleDateFormat
相对于今天的 -80 年到 +20 年的范围。
如果你想配置它那么你必须使用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
.关于您没有任何其他与周相关的字段这一事实,我假设是正常的日历年,而不是基于周的日历年。
关于java - 将字符串解析为本地日期不使用所需的世纪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29490893/