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?
Java 8 LocalDate may be used:
If input argument is
"2011/12/12aaaaaaaaa"
, output isfalse
;If input argument is
"2011/12/12"
, output istrue
The JavaDoc on
parse(...)
states the following:It seems like you can't make
SimpleDateFormat
throw an exception, but you can do the following: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.
Have a look on the following class which can check whether the date is valid or not
** Sample Example**
Take a look on the method documentation which says:
ParseException if the beginning of the specified string cannot be parsed
.Method source code with javadoc:
You can use the
ParsePosition
class or thesdf.setLenient(false)
functionDocs: http://docs.oracle.com/javase/7/docs/api/java/text/ParsePosition.html http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)
After it successfully parsed the entire pattern string
SimpleDateFormat
stops evaluating the data it was given to parse.