2

Possible Duplicate:
How do I calculate someone's age in Java?

I want to calculate the user age , and my method doesnt give the correct age in case if the month of birth is equal to the current month and the day of birth less than or equal the current day ( if the user enter his birth date through the date picker as 9/4/1990 or 4/4/1990 the age will be 21 not 22) how i can solve this problem ? what is the update i should do to get the correct age in this case ? please help me ....

this is my method

public static  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;  
}
Community
  • 1
  • 1
user
  • 631
  • 14
  • 45

2 Answers2

4

There are two problems with your code:

  • if the date of birth is 9th April 1990, you need to write dob.set(1990,3,9) as months start at 0 ==> you probably need dob.set(year, month - 1, day);
  • if the current year is a leap year and not the year of birth (or vice versa) and dates are after the 28/29 Feb, you will get 1 day difference on an identical date.

This seems to work but you should test it with various scenarios and make sure you are happy with the result:

public static String getAge(int year, int month, int day) {
    Calendar dob = Calendar.getInstance();
    Calendar today = Calendar.getInstance();


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

    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)) {
        if (today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) {
            age--;
        }
    }

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

    return ageS;

}

And a (very simplified) test:

public static void main(String[] args) { //today = 8 April 2012
    System.out.println(getAge(1990,3,7)); //22
    System.out.println(getAge(1990,3,8)); //22
    System.out.println(getAge(1990,3,9)); //22
    System.out.println(getAge(1990,4,7)); //22
    System.out.println(getAge(1990,4,8)); //22
    System.out.println(getAge(1990,4,9)); //21
    System.out.println(getAge(1990,5,7)); //21        
    System.out.println(getAge(1990,5,8)); //21        
    System.out.println(getAge(1990,5,9)); //21        
}
assylias
  • 297,541
  • 71
  • 621
  • 741
-2

You can compute the difference by transforming both dates in milliseconds and than in a Date object for example. Code would be something like this:

long ageMilis = today.getTimeInMillis() - dob.getTimeInMillis();
Date age = new Date(ageMilis);
return age.toString();
azertiti
  • 3,090
  • 14
  • 19