views:

3223

answers:

3

I want to return an age in years as an int in a Java method. What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):

public int getAge() {
 long ageInMillis = new Date().getTime() - getBirthDate().getTime();

 Date age = new Date(ageInMillis);

 return age.getYear();
}

But since getYear() is deprecated I'm wondering if there is a better way to do this? I'm not even sure this works correctly, since I have no unit tests in place (yet).

+6  A: 

Your example is NOT the way to do it.

Take a look at this.

The JODA datetime library has some nice interval calculations. Try that.

duffymo
Your answer would be more helpful if it contained an example in code...
johnstok
That's what the first link shows.
duffymo
+5  A: 
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(...);
if (dob.after(now)) {
  throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
int age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
  age--;
} else if (month1 == month2) {
  int day1 = now.get(Calendar.DAY_OF_MONTH);
  int day2 = dob.get(Calendar.DAY_OF_MONTH);
  if (day2 > day1) {
    age--;
  }
}
// age is now correct
cletus
This does not work if someone is born, for example, 31-12-2008 and today is 1-1-2009 (or any other dates where the person hasn't had this year's birthday)
Jorn
You're right. Got the comparisons the wrong way round. Fixed.
cletus
+7  A: 

Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).

e.g.

DateMidnight birthdate = new DateMidnight(1970, 1, 20);
DateTime now = new DateTime();
Years age = Years.betweenYears(birthdate, now);

which is as simple as you could want. The current Java stuff is (as you've identified) somewhat unintuitive.

Brian Agnew