Simple Strict Date Parsing

In Java, the DateFormat.parse() method is a funny little critter. It helps you by trying to figure out what date you actually meant when you typed in “35/12/2O10” (note the letter “O” in 2O10). In this case, it will parse the date without errors or warnings, and returns the date “11/12/04” (November 12th, 0004). That’s because it thinks “35” is a month, and “2” is the year, ignoring everything after the letter “O”.

DateFormat tries to convert the “35th month” into 2 years and 11 months, and correct the date accordingly. df.setLenient(false) prevents this, but that still leaves the problem of the parsing stopping at the first wrong character without warning.

I needed a much stricter way of parsing dates, and yesterday I found an elegant solution to this problem. It’s so small I was able to tweet it in less than 140 characters, but I thought it deserved a decent blogpost so here it goes:

public Date parseDateString(String inputDateString) 
         throws ParseException {
  DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
  Date parsedDate = df.parse(inputDateString);

  if (!inputDateString.equals(df.format(parsedDate))) {
    throw new ParseException("Invalid Date", 0);
  return parsedDate;

The brilliance here is in the comparing of the formatted date with the original input. The method returns a normal ParseException so you can perfectly replace your original df.parse() calls with it, making them more strict.

Thanks to Bas for this elegant and simple solution.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s