[英]Parsing string to local date doesn't use desired century
I am using this DateTimeFormatter: 我正在使用这个DateTimeFormatter:
DateTimeFormatter.ofPattern("ddMMYY")
I want to parse the string 150790
and I got this error: 我想解析字符串150790
,我收到此错误:
Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=15, MonthOfYear=7, WeekBasedYear[WeekFields[MONDAY,4]]=2090},ISO of type java.time.format.Parsed
Obviously, I want to get the following TemporalAccessor
: 显然,我想获得以下TemporalAccessor
:
{DayOfMonth=15, MonthOfYear=7, WeekBasedYear=1990}
Do you know why I got the year 2090 instead of 1990? 你知道我为什么得到2090而不是1990年?
Thanks for your help 谢谢你的帮助
Since this question is really about new java.time
-package and NOT SimpleDateFormat
I will cite following relevant section : 由于这个问题实际上是关于新的java.time
而不是SimpleDateFormat
我将引用以下相关部分 :
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. 如果字母数是2,则使用减少的两位数形式。 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. 对于解析,这将使用2000的基值进行解析,从而产生2000到2099(包括2000和2099)范围内的一年。
We see that Java-8 uses the range 2000-2099 per default , not like SimpleDateFormat
the range -80 years until +20 years relative to today. 我们看到Java-8 默认使用2000-2099的范围,而不是像SimpleDateFormat
的范围 - 相对于今天的20年直到+ 20年。
If you want to configure it then you have to use appendValueReduced() . 如果要配置它,则必须使用appendValueReduced() 。 This is designed in an inconvenient way, but possible, see here: 这是一个不方便的设计,但可能,请看这里:
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
By the way, if you really want week-based years then you have to use Y instead of y or the appropriate field IsoFields.WEEK_BASED_YEAR
. 顺便说一句,如果你真的想要基于周的年份,那么你必须使用Y而不是y或相应的字段IsoFields.WEEK_BASED_YEAR
。 Regarding the fact that you don't have any other week-related fields I would assume the normal calendar year, not the week-based one. 关于您没有任何其他与周相关的字段的事实,我会假设正常的日历年,而不是基于周的日历年。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.