Pooja
Pooja

Reputation: 241

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

Upvotes: 2

Views: 10641

Answers (2)

user2864740
user2864740

Reputation: 61875

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.

Upvotes: 3

Ketan Ahir
Ketan Ahir

Reputation: 6738

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

Upvotes: 9

Related Questions