Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

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.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!