解析字符串到本地日期不使用所需的世纪 [英] Parsing string to local date doesn't use desired century
问题描述
我正在使用DateTimeFormatter:
I am using this DateTimeFormatter:
DateTimeFormatter.ofPattern("ddMMYY")
我想解析字符串 150790
这个错误:
I want to parse the string 150790
and I got this error:
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年?
Do you know why I got the year 2090 instead of 1990?
感谢您的帮助
推荐答案
由于这个问题真的是关于新的 java.time
-package and NOT SimpleDateFormat
我将引用以下相关部分:
Since this question is really about new java.time
-package and NOT SimpleDateFormat
I will cite following relevant section:
年份:字母数决定最小字段宽度低于
使用的是padding。如果字母数为2,则使用缩减的
两位数形式。对于打印,这将输出最右边的两个
数字。为了解析,这将使用基础值2000,
进行解析,导致2000到2099之间的一年。
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年相对到今天。
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.
如果要配置它,则必须使用 appendValueReduced()。这是以不方便的方式设计的,但可能会出现在这里:
If you want to configure it then you have to use 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
顺便说一句,如果你真的想要周几年,那么你必须使用Y代替y或适当的字段 IsoFields.WEEK_BASED_YEAR
。关于你没有任何其他周相关领域的事实,我将承担正常的日历年,而不是基于周的一年。
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
. 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.
这篇关于解析字符串到本地日期不使用所需的世纪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!