Tag Archives: gotcha

Java Gotcha: Parse string using SimpleDateFormat with months greater than 12

I was the other day trying to parse a date string into a date object using SimpleDateFormat to check for the validity of the date string. I had the SimpleDateFormat defined as: SimpleDateFormat expiryDateFormat = new SimpleDateFormat("dd/MM/yyyy");. The date string I was trying to parse was: 10/26/2016 which is clearly invalid with respect to the pattern defined in the SimpleDateFormat. I found that the parsing went through and then it failed while trying to insert into DB due to invalid date. I was utterly confused. Then I wrote a small program to isolate the issue with SimpleDateFormat:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Solution {

  public static void main(String[] args) {

    SimpleDateFormat expiryDateFormat = 
        new SimpleDateFormat("dd/MM/yyyy");
    try {
      Date date =expiryDateFormat.parse("10/26/2016");
      System.out.println(date);
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }
}

The above code gave an output: Sat Feb 10 00:00:00 AST 2018. I was surprised at this behavior. Then I uncovered a secret method setLenient() using which we can put the SimpleDateFormat parsing to be strict and report errors on slightest of mismatch and not try to interpret the input by adjusting the value. So an updated code looks like:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Solution {

  public static void main(String[] args) {

    SimpleDateFormat expiryDateFormat = 
        new SimpleDateFormat("dd/MM/yyyy");
    expiryDateFormat.setLenient(false);
    try {
      Date date =expiryDateFormat.parse("10/26/2016");
      System.out.println(date);
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }
}

which indeed throws an exception as expected:

java.text.ParseException: Unparseable date:"10/26/2016"
	at java.text.DateFormat.parse(DateFormat.java:366)
	at Solution.main(Solution.java:12)
Advertisements