Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 686
MetroidFan2002 Avatar asked Jan 28 '09 21:01

MetroidFan2002


People also ask

How do you Hardcode a date in Java?

Date date1 = new SimpleDateFormat("dd/MM/yyyy"). parse("10/12/2018"); It is showing the exact date.

What is strict parsing?

Strict parsing requires that the format and input match exactly, including delimiters. dayjs('1970-00-00', 'YYYY-MM-DD').isValid() // true dayjs('1970-00-00', 'YYYY-MM-DD', true).isValid() // false dayjs('1970-00-00', 'YYYY-MM-DD', 'es', true).isValid() // false.

What is lenient in Java?

Leniency refers to whether or not a strict rule will be applied at parsing. If a DateFormat object is lenient, it will accept Jan 32, 2005. In fact, it will take the liberty of converting it to Feb 1, 2006. By default, a DateFormat object is lenient.


2 Answers

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!

like image 200
yawmark Avatar answered Nov 15 '22 16:11

yawmark


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.

like image 43
Rolf Avatar answered Nov 15 '22 17:11

Rolf