How do I calculate someone's age in Java?

nojevive picture nojevive · Jul 12, 2009 · Viewed 310.5k times · Source

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).

Answer

Brian Agnew picture Brian Agnew · Jul 12, 2009

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).

EDIT: Java 8 has something very similar and is worth checking out.

e.g.

LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);

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