I have found nice function which is validating the format and correctness of date String
. I wanted to upgrade it to validate only >= 1900
years.
So this is what I found:
public boolean isDateValid(String date) {
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
df.setLenient(false);
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
And this is my upgraded version:
public boolean isDateValid(String date) {
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
df.setLenient(false);
df.parse(date);
Integer year = Integer.parseInt(date.substring(6, 10));
if (year>= 1900)
return true;
else
return false;
} catch (ParseException e) {
return false;
}
}
So instead of returning true I am checking if the year
variable is greater or equal to 1900. The problem is when I run this function with "12-12-1xxx"
(edit: or "12-12-1abc"
). NumberFormatException
is thrown while parsing year String
to int
. It definitely should not happen because ParseException
should be thrown first, breaking the try {}
block.
It looks like validation from first listing does not work properly because it accepts every "yyyy"
part which begins with a number. Yet everything works fine for "12-12-xxxx"
(edit: or "12-12-abcd"
).
EDIT:
Stop voting down my question and focus while you are reading. The question is very clear: why new SimpleDateFormat("dd-MM-yyyy").parse("12-12-1xxx") does not throw a ParseException?