Reputation: 57
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?
Upvotes: 0
Views: 5349
Reputation: 19
Add this additional check after parsing each string:
Upvotes: 0
Reputation: 10218
I think your code is fine (but not very scalable - try to do it in a for-loop in case you add more formats later).
The problem is that your format strings are wrong. Instead of dd-MM-yyyy
you should have dd/MM/yyyy
. The same goes for the rest of the formats:
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");
Upvotes: 1
Reputation: 66637
Your input is in the format 2/09/2012 not 2-09-2012, so your dateformat should be like below:
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");
Upvotes: 2