javajdk6

Prevent invalid date from getting converted into date of next month in jdk6?


Consider the snippet:

String dateStr = "Mon Jan 32 00:00:00 IST 2015";    // 32 Jan 2015

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));

gives me the output as

01.02.2015     //   Ist February 2015

I wish to prevent this to make the user aware on the UI that is an invalid date?
Any suggestions?


Solution

  • The option setLenient() of your SimpleDateFormat is what you are looking for.

    After you set isLenient to false, it will only accept correctly formatted dates anymore, and throw a ParseException in other cases.

    String dateStr = "Mon Jan 32 00:00:00 IST 2015";    // 32 Jan 2015
    
    DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    formatter.setLenient(false);
    DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
    try {
        System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
    } catch (ParseException e) {
        // Your date is invalid
    }