2

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;    
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Pooja
  • 241
  • 2
  • 3
  • 11
  • This might help you http://stackoverflow.com/questions/12871173/how-to-set-min-max-age-limit-with-datepicker-android – GrIsHu Dec 24 '13 at 04:42

2 Answers2

9

you can use this method to get age

/**
 * calculates age from birth date
 * 
 * @param selectedMilli
 */
private void getAge(long selectedMilli) {
    Date dateOfBirth = new Date(selectedMilli);
    Calendar dob = Calendar.getInstance();
    dob.setTime(dateOfBirth);
    Calendar today = Calendar.getInstance();
    int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
    if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
        age--;
    } else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
            && today.get(Calendar.DAY_OF_MONTH) < dob
                    .get(Calendar.DAY_OF_MONTH)) {
        age--;
    }

    if (age < 18) {
        //do something
    } else {

    }

    str_age = age + "";
    Log.d("", getClass().getSimpleName() + ": Age in year= " + age);
}
Ketan Ahir
  • 6,678
  • 1
  • 23
  • 45
3

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.
user2864740
  • 60,010
  • 15
  • 145
  • 220