Is there a good *strict* date parser for Java?

吃可爱长大的小学妹 提交于 2019-11-27 23:00:30

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!

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.

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.

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