问题
Is there a good, strict date parser for Java? I have access to Joda-Time but I have yet to see this option. I found the "Is there a good date parser for Java" question, and while this is related it is sort of the opposite. Whereas that question was asking for a lenient, more fuzzy-logic and prone to human error parser, I would like a strict parser. For example, with both JodaTime (as far as I can tell) and simpleDateFormat, if you have a format "MM/dd/yyyy":
parse this: 40/40/4353
This becomes a valid date. I want a parser that knows that 40 is an invalid month and date. Surely some implementation of this exists in Java?
回答1:
I don't see that Joda recognizes that as a valid date. Example:
strict = org.joda.time.format.DateTimeFormat.forPattern("MM/dd/yyyy")
try {
strict.parseDateTime('40/40/4353')
assert false
} catch (org.joda.time.IllegalFieldValueException e) {
assert 'Cannot parse "40/40/4353": Value 40 for monthOfYear must be in the range [1,12]' == e.message
}
As best as I can tell, neither does DateFormat with setLenient(false). Example:
try {
df = new java.text.SimpleDateFormat('MM/dd/yyyy')
df.setLenient(false)
df.parse('40/40/4353')
assert false
} catch (java.text.ParseException e) {
assert e.message =~ 'Unparseable'
}
Hope this helps!
回答2:
A good way to do strict validation with DateFormat is re-formatting the parsed date and checking equality to the original string:
String myDateString = "87/88/9999";
Date myDate = dateFormat.parse(myDateString);
if (!myDateString.equals(df.format(myDate))){
throw new ParseException();
}
Works like a charm.
回答3:
You can use the apache.commons.validator.routines.DateValidator
to validate the date,if you do not want to use SimpleDateFormat
.
Example :
public static Date validateDate(String value, String pattern) {
DateValidator validator = new DateValidator();
Date date = null;
if (pattern!=null) { //Pattern is passed
date = validator.validate(value, pattern);
} else {
date = validator.validate(value);
}
return date;
}
So if a null is returned it means that the date is not valid otherwise it's a valid date.This method is an alternative to using the SimpleDateFormat
as you don't have to rely on exception being thrown to identify if it's a valid date or not.
来源:https://stackoverflow.com/questions/489538/is-there-a-good-strict-date-parser-for-java