I have to do a validation in Date field which must be 18 years less than current date else it must show error.
public static boolean dobdateValidate(String date) {
boolean result = false;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
try {
Date parseddate = sdf.parse(date);
Calendar c2 = Calendar.getInstance();
c2.add(Calendar.DAY_OF_YEAR, -18);
Date dateObj2 = new Date(System.currentTimeMillis());
if (parseddate.before(c2.getTime())) {
result = true;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
The core issue is that Calendar.DAY_OF_YEAR
is not correct as "[DAY_OF_YEAR indicates] the day number within the current year".
Use Calendar.YEAR
instead.
Other suggestions:
dateObj2
variable is never used and should be removed.