17

I want to write a method to calculate the age from the birth date, is the logic correct and how to write it in android Java:

public int calculateAge(String birthday){ 
 // consider that birthday format is ddmmyyyy;

 String today = SystemDate(ddmmyyyy);
 int bDay = birthday(1,2).toInteger;
 int bMonth = birthday(3,4).toInteger;
 int bYear = birhtday(5,8).toInteger;

 int tDay = today(1,2).toInteger;
 int tMonth = today(3,4).toInteger;
 int tYear = today(5,8).toInteger;

 if (tMonth == bMonth){
     if (tday>= bDay){ 
        age = tYear - bYear;
      else 
        age = tYear - bYear - 1;}
 else
   if (tMonth > bMonth) {
       age = tYear - bYear;
   else 
       age = tYear - bYear - 1;}
 }
 return age;
}
Richard
  • 6,438
  • 5
  • 43
  • 58
Heba
  • 209
  • 1
  • 2
  • 10

7 Answers7

53

Here is my solution to the problem:

/**
 * Method to extract the user's age from the entered Date of Birth.
 * 
 * @param DoB String The user's date of birth.
 * 
 * @return ageS String The user's age in years based on the supplied DoB.
 */
private String getAge(int year, int month, int day){
    Calendar dob = Calendar.getInstance();
    Calendar today = Calendar.getInstance();

    dob.set(year, month, 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--; 
    }

    Integer ageInt = new Integer(age);
    String ageS = ageInt.toString();

    return ageS;  
}

I used a DatePicker to get the input values required here. This method, together with the date picker, is specifically to get the user's DoB and calculate their age. A slight modification can be made to allow for String input(s) of the user's DoB, depending upon your specific implementation. The return type of String is for updating a TextView, a slight mod can be made to allow for type int output also.

Kingsolmn
  • 1,858
  • 2
  • 23
  • 39
  • I like your way in using the day_of_year, smart :) – Heba Mar 15 '11 at 06:55
  • I used a DatePicker to get DOB,too, but I convert it to string in order to store it in the database (SQLite), and every time I need the age for calculation I return the dob as an argument, so I add the substring method to get the year, month and day. – Heba Mar 15 '11 at 06:56
  • I built this solution using bits and pieces of answers on SO, I believe the `Calendar.DAY_OF_YEAR` came from a answer that pointed to www.coderanch.com. Enjoy! – Kingsolmn Mar 15 '11 at 16:26
  • Glad to return the help I find on SO! – Kingsolmn May 01 '11 at 22:12
  • @Kingsolmn im sorry to say but your algo is wrong,your are not checking the month case – Muhammad Babar Apr 09 '13 at 10:28
  • @MuhammadBabar how do you mean? – Kingsolmn Jun 15 '13 at 14:35
  • your solutions fails when current month is equals to d.o.b month but current day is less than d.o.b day, please see my answer below – Muhammad Babar Jun 17 '13 at 06:13
  • 1
    Ok, I get what you're saying now. However, the case you are describing is why I opted to use the `Calendar.DAY_OF_YEAR` field. Just a different approach to the same solution is all. The best approach should be determined, in part, by the implementation. That and personal preference and style. – Kingsolmn Jun 17 '13 at 14:44
  • Not working for this date : 27-11-1989 , I am getting 26 year but actually i am 27 year old – Mahesh Kavathiya Dec 07 '16 at 06:42
16

This works Perfectly.....

public int getAge(int DOByear, int DOBmonth, int DOBday) {

        int age;

        final Calendar calenderToday = Calendar.getInstance();
        int currentYear = calenderToday.get(Calendar.YEAR);
        int currentMonth = 1 + calenderToday.get(Calendar.MONTH);
        int todayDay = calenderToday.get(Calendar.DAY_OF_MONTH);

        age = currentYear - DOByear;

        if(DOBmonth > currentMonth) {
            --age;
        } else if(DOBmonth == currentMonth) {
            if(DOBday > todayDay){
                --age;
            }
        }
        return age;
    }
W I Z A R D
  • 1,214
  • 3
  • 17
  • 42
  • 4
    It's work fine...above all example are giving wrong age when you enter 27-11-1989, My age is 27 but it shows 26... – Mahesh Kavathiya Dec 07 '16 at 06:41
  • 1
    Yes. other answers are wrong on current birth month. The age change affects once the only birth month over. But this code from the day. – Fahry Mohammed Apr 27 '18 at 06:17
  • this must be accepted answer...works perfectly even in current month bday too..all above answers doesnt give me accurate answer when bday is in current month. – Android Geek Feb 24 '20 at 09:16
6

Here's an example android age calculation that you should be able to work from:

    public int getAge (int _year, int _month, int _day) {

            GregorianCalendar cal = new GregorianCalendar();
            int y, m, d, a;         

            y = cal.get(Calendar.YEAR);
            m = cal.get(Calendar.MONTH);
            d = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(_year, _month, _day);
            a = y - cal.get(Calendar.YEAR);
            if ((m < cal.get(Calendar.MONTH))
                            || ((m == cal.get(Calendar.MONTH)) && (d < cal
                                            .get(Calendar.DAY_OF_MONTH)))) {
                    --a;
            }
            if(a < 0)
                    throw new IllegalArgumentException("Age < 0");
            return a;
    }
Jon Egerton
  • 38,633
  • 11
  • 95
  • 128
1

Here is the fully tested and working code

Below is an example using date picker dialog

@Override
    public void onDateSet(DatePicker view, int mBirthYear, int mMonthOfYear, int mDayOfMonth) 
    {
            mAge = year - mBirthYear;

            if( (mMonthOfYear == month && day < mDayOfMonth) || ( month < mMonthOfYear) ) 
            {
                mAge--;
            }

            String years = getString(R.string.years);

            etAge.setText(mAge+years);      

    }
Muhammad Babar
  • 7,984
  • 5
  • 36
  • 53
0

None of the posted solutions worked for me. So, I worked my own logic and got this, which works 100% for me:

 Integer getAge(Integer year, Integer month, Integer day) {
     Calendar dob = Calendar.getInstance();
     Calendar today = Calendar.getInstance();

     dob.set(year, month, day);
     int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

     if(month == (today.get(Calendar.MONTH)+1) && day > today.get(Calendar.DAY_OF_MONTH)) {
         age--;
     }

     return age;
 }
0
private String getAge(int year, int month, int day){

  Calendar dob = Calendar.getInstance();

  Calendar today = Calendar.getInstance();

  dob.set(year, month, day);

  today.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH) + 1,
    today.get(Calendar.DATE));

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

  if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {

    age--;

  }

  Integer ageInt = new Integer(age);

  String ageS = ageInt.toString();

  return ageS;
}
PrakashExplorer
  • 141
  • 1
  • 8
0

The below will provide you age in the most accurate way possible

public static String getAgeFromLong(String birthday) {

    SimpleDateFormat sdf= new SimpleDateFormat("ddMMyyyy",Locale.ENGLISH);
    Calendar dobCal=Calendar.getInstance();
    dobCal.setTime(sdf.parse(birthday));

    Calendar diffCal = Calendar.getInstance();
    diffCal.setTimeInMillis(Calendar.getInstance().getTimeInMillis() - dobCal.getInstance().getTimeInMillis());

    String ageS = "";

    int age = diffCal.get(Calendar.YEAR) - 1970;
    //Check if less than a year
    if (age == 0) {
        age = diffCal.get(Calendar.MONTH);
        //Check if less than a month
        if (age == 0) {
            age = diffCal.get(Calendar.WEEK_OF_YEAR);
            //Check if less than a week
            if (age == 1) {
                age = diffCal.get(Calendar.DAY_OF_YEAR);
                ageS = (age - 1) + " Days";
            } else {
                ageS = (age - 1) + " Weeks";
            }
        } else {
            ageS = age + " Months";
        }
    } else {
        ageS = age + " Years";
    }

    return ageS;
}
Vishwajit Palankar
  • 2,941
  • 3
  • 27
  • 46