Search code examples
javadatesimpledateformatdate-parsingparseexception

23/12/2013 is mapping with MM/dd/yyyy format why, why not ParseException


Can anybody help?

public void dateCalender() throws ParseException{
        System.out.println(new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse("120/12/2013").toString()); //OUTPUT (Unexpected): Mon Dec 12 00:00:00 IST 2022
        System.out.println(new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse("23/12/2013").toString()); //OUTPUT (Unexpected): Wed Nov 12 00:00:00 IST 2014
        System.out.println(new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse("Jan/12/2013").toString()); //OUTPUT (Expected): Unparseable date: "Jan/12/2013"
    }

Solution

  • You have to invoke setLenient with false - otherwise SimpleDateFormat will try to "figure out" what month that is. So, first create SimpleDateFormat and invoke sdf.setLenient(false). Now when parsing, you will get exception.