I want to create a method to validate a date by using SimpleDateFormat.
If the date is valid(e.g. 02/09/2012 or 2/09/2012 or 02/9/2012), this method should return true.
But if the format of the date is wrong(e.g. 02/09/201X) or logically wrong(e.g. 32/09/2012), this method should return false.
I try to write this method like this:
private boolean isValidDate(String date) {
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
DateFormat df2 = new SimpleDateFormat("d-MM-yyyy");
DateFormat df3 = new SimpleDateFormat("dd-M-yyyy");
Date d = null;
String s = null;
try {
d = df1.parse(date);
}catch (Exception e1) {
try{
d = df2.parse(date);
}catch (Exception e2) {
try {
d= df3.parse(date);
}catch (Exception e3) {
return false;
}
s = df3.format(d);
return date.equals(s);
}
s = df2.format(d);
return date.equals(s);
}
s = df1.format(d);
return date.equals(s);
}
But if I validate a date, for instance, 2/09/2012, it returns false (actually it should return true). I have no idea why… Can anyone find what’s the problem with my code, or this logic is totally wrong? Is there any better way to do this validation?
Your input is in the format 2/09/2012 not 2-09-2012, so your dateformat should be like below: