Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - DateTimeFormatter auto-corrects invalid (syntactically possible) calendar date

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...