javasimpledateformatparseexception

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


Here is an example:

public MyDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
    sdf.setLenient(false);
    String t1 = "2011/12/12aaa";
    System.out.println(sdf.parse(t1));
}

2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.

Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?


Solution

  • 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.