Get Age from Date of Birth in Java Android

Here is how to get a user’s age from date of birth

If you need get a user’s age from a given date of birth string, this code below can be used for that

The date of birth string must be in DD/MM/YYYY format

  private int getAge(String dobString){

        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            date = sdf.parse(dobString);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if(date == null) return 0;

        Calendar dob = Calendar.getInstance();
        Calendar today = Calendar.getInstance();

        dob.setTime(date);

        int year = dob.get(Calendar.YEAR);
        int month = dob.get(Calendar.MONTH);
        int day = dob.get(Calendar.DAY_OF_MONTH);

        dob.set(year, month+1, day);

        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

        if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
            age--;
        }
        return age;
}

When you call this, it will return the age based on the string you provided.

If you need any help or you need any type of android apps and games developed, we can develop it for you, just contact usĀ 

Post navigation

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.