Search code examples
javaandroiddateandroid-datepicker

Date validation to be less than 18 years from current date in android


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;    
    }

Solution

  • 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:

    • The dateObj2 variable is never used and should be removed.
    • Return directly instead of using an intermediate flag variable.
    • Take in a Date/Calendar object and leave the caller responsible for parsing.