Calculate Age from date of birth in Java

This tutorial demonstrates how to calculate the age from a birth date in Java. Something trivial as calculating the age, was daunting before Joda Time and Java 8. Let’s list the options you have to calculate the age from date of birth in Java.

Joda Time

import org.joda.time.LocalDate;
import org.joda.time.Years;

LocalDate birthday = new LocalDate(1989, 12, 6);
LocalDate now = new LocalDate(2016, 10, 11);
Years age = Years.yearsBetween(birthday, now);

System.out.println("age: " + age.getYears());  // prints "age: 26"

Java 8

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.temporal.ChronoUnit;

LocalDate birthday = LocalDate.of(1989, Month.DECEMBER, 6);
LocalDate now = LocalDate.of(2016, Month.OCTOBER, 11);

// using period
Period period = Period.between(birthday, now);
System.out.println(period.getDays());
System.out.println(period.getMonths());
System.out.println("age: " + period.getYears());  // prints "age: 26"

// using chrono unit
System.out.println("age: " + ChronoUnit.YEARS.between(birthday, now));  // prints "age: 26"

Plain Java

import java.util.Calendar;
import java.util.Date;

public static void main(String... args){
    Calendar birthday = Calendar.getInstance();
    birthday.set(1989, 12, 6);
    System.out.println("age: " + getAge(birthday.getTime()));  // prints "age: 26"
}

public static int getAge(Date dateOfBirth) {
    Calendar today = Calendar.getInstance();
    Calendar birthDate = Calendar.getInstance();
    birthDate.setTime(dateOfBirth);
    if (birthDate.after(today)) {
        throw new IllegalArgumentException("You don't exist yet");
    }
    int todayYear = today.get(Calendar.YEAR);
    int birthDateYear = birthDate.get(Calendar.YEAR);
    int todayDayOfYear = today.get(Calendar.DAY_OF_YEAR);
    int birthDateDayOfYear = birthDate.get(Calendar.DAY_OF_YEAR);
    int todayMonth = today.get(Calendar.MONTH);
    int birthDateMonth = birthDate.get(Calendar.MONTH);
    int todayDayOfMonth = today.get(Calendar.DAY_OF_MONTH);
    int birthDateDayOfMonth = birthDate.get(Calendar.DAY_OF_MONTH);
    int age = todayYear - birthDateYear;

    // If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
    if ((birthDateDayOfYear - todayDayOfYear > 3) || (birthDateMonth > todayMonth)){
        age--;
    
    // If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
    } else if ((birthDateMonth == todayMonth) && (birthDateDayOfMonth > todayDayOfMonth)){
        age--;
    }
    return age;
}

You may also like...