DateTimeFormatter auto-corrects invalid (syntactically possible) calendar date

非 Y 不嫁゛ 提交于 2019-11-28 09:21:14

问题


Java DateTimeFormatter throws an exception for when you try a date that goes outside of a possible range, for example:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy");
String dateString = "12/32/2015";
LocalDate ld = LocalDate.parse(dateString, dtf);

will throw:

Exception in thread "main" java.time.format.DateTimeParseException: Text '12/32/2015' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 32

But when I enter an invalid calendar date that is still syntactically possible by their standards, it autocorrects it to be a valid date, for example:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy");
String dateString = "2/31/2015";
LocalDate ld = LocalDate.parse(dateString, dtf);

it successfully parses but autocorrects to 2015-02-28. I don't want this behavior, I want it to still throw an exception when the date is not a valid calendar date. Is there a built-in option I can set for that to happen, or do I really have to try to manually sift out these instances?


回答1:


You can use a STRICT resolver style:

import static java.time.format.ResolverStyle.STRICT;

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uuuu").withResolverStyle(STRICT);

By default, ofPattern uses a SMART resolver style which will use reasonable defaults.

Note that I have used uuuu instead of yyyy, i.e. YEAR instead of YEAR_OF_ERA. Assuming you are in a Gregorian calendar system, the two are equivalent for years in the current era (year 1 or greater). The difference is explained in more details in the links above.



来源:https://stackoverflow.com/questions/30308122/datetimeformatter-auto-corrects-invalid-syntactically-possible-calendar-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!