1. Overview
In this quick tutorial, we’ll see how to calculate age using Java 8, Java 7 and Joda-Time libraries.
In all cases, we’ll take the birth date and current date as input and return the calculated age in years.
2. Using Java 8
Java 8 introduced a new Date-Time API for working with dates and times, largely based off of the Joda-Time library.
In Java 8, we can use java.time.LocalDate for our birth date and current date, and then use Period to calculate their difference in years:
public int calculateAge( LocalDate birthDate, LocalDate currentDate) { // validate inputs ... return Period.between(birthDate, currentDate).getYears(); }
LocalDate is helpful here because represents just a date, compared to Java’s Date class, which represents both a date and a time. LocalDate.now() can give us the current date.
And Period is helpful when we need to think about time periods in years, months and days.
If we wanted to get a more exact age, say in seconds, then we’d want to take a look at LocalDateTime and Duration, respectively (and maybe return a long instead).
3. Using Joda-Time
If Java 8 isn’t an option, we can still get the same kind of result from Joda-Time, a de-facto standard for date-time operations in the pre-Java 8 world.
We need to add the Joda-Time dependency to our pom:
<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10</version> </dependency>
And then we can write a similar method to calculate age, this time using LocalDate and Years from Joda-Time:
public int calculateAgeWithJodaTime( org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) { // validate inputs ... Years age = Years.yearsBetween(birthDate, currentDate); return age.getYears(); }
4. Using Java 7
Without a dedicated API in Java 7, we are left to roll our own, and so there are quite a few approaches.
As one example, we can use java.util.Date:
public int calculateAgeWithJava7( Date birthDate, Date currentDate) { // validate inputs ... DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); int d1 = Integer.parseInt(formatter.format(birthDate)); int d2 = Integer.parseInt(formatter.format(currentDate)); int age = (d2 - d1) / 10000; return age; }
Here, we convert the given birthDate and currentDate objects into integers and find the difference between them, and so long as we aren’t still on Java 7 in 8000 years, this approach should work until then.
5. Conclusion
In this article, we showed out how to calculate age easily using Java 8, Java 7 and Joda-Time libraries.
To learn more about Java 8’s data-time support check out our Java 8 date-time intro.
And as always, the complete code for these snippets can be found over on GitHub.