SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?

The JavaDoc on parse(...) states the following:

parsing does not necessarily use all characters up to the end of the string

It seems like you can't make SimpleDateFormat throw an exception, but you can do the following:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
ParsePosition p = new ParsePosition( 0 );
String t1 = "2011/12/12aaa";    
System.out.println(sdf.parse(t1,p));

if(p.getIndex() < t1.length()) {
  throw new ParseException( t1, p.getIndex() );
}

Basically, you check whether the parse consumed the entire string and if not you have invalid input.


To chack whether a date is valid The following method returns if the date is in valid otherwise it will return false.

public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

Have a look on the following class which can check whether the date is valid or not

** Sample Example**

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

public class DateValidCheck {


    public static void main(String[] args) {

        if(new DateValidCheck().isValidDate("2011/12/12aaa")){
            System.out.println("...date is valid");
        }else{
            System.out.println("...date is invalid...");
        }

    }


    public boolean isValidDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }
        catch (ParseException e) {
            return false;
        }
        if (!sdf.format(testDate).equals(date)) {
            return false;
        }
        return true;

    }

}

After it successfully parsed the entire pattern string SimpleDateFormat stops evaluating the data it was given to parse.