Calculate Age from Birth Date in Java Calculate Age from Birth Date in Java

Page content

In this quick tutorial, we’ll learn how to calculate the age in human readable format in Java.

Requirement

We want to create a utility method in Java which calculate the age from birth date as of today in human readable format i.e. in Years, Months, and Days.

These are few examples of expected age as of date 2024-01-01 from the given birth date:-

Birth Date As of date Age
2000-01-01 2024-01-01 24 Years
1990-05-01 2024-01-01 33 Years and 8 Months
1980-08-22 2024-01-01 43 Years, 4 Months and 10 Days

Let’s build a utility method to achieve this.

Date Utlity Method

Let’s create a utility method DateUtils.calculateAge(birthDate) to calculate age from birth date as of today in human readable format i.e. in Years, Months, and Days.

package com.example.util;

import java.time.LocalDate;
import java.time.Period;

public class DateUtils {

  public static String calculateAge(LocalDate birthDate) {
    return getDiffInHumanReadableFormat(birthDate, LocalDate.now());
  }

  public static String getDiffInHumanReadableFormat(LocalDate startDate, LocalDate endDate) {
    Period period = Period.between(startDate, endDate);
    StringBuilder token = new StringBuilder();
    appendUnits(token, period.getYears(), "Year");
    yearSeparator(period, token);
    appendUnits(token, period.getMonths(), "Month");
    monthSeparator(period, token);
    appendUnits(token, period.getDays(), "Day");
    return token.toString().trim();
  }

  private static void appendUnits(StringBuilder token, int units, String unitName) {
    if (units > 0) {
      token.append(units).append(" ").append(unitName);
      if (units > 1) token.append("s");
    }
  }

  private static void yearSeparator(Period period, StringBuilder token) {
    if (period.getYears() > 0 && period.getMonths() > 0) {
      token.append(period.getDays() > 0 ? ", " : " and ");
    }
  }

  private static void monthSeparator(Period period, StringBuilder token) {
    boolean appendAnd = (period.getMonths() > 0 && period.getDays() > 0) ||
            (period.getMonths() == 0 && period.getYears() > 0 && period.getDays() > 0);
    if (appendAnd) token.append(" and ");
  }
}

Let’s call the utility method to calculate Age:-

LocalDate birthDate = LocalDate.of(1980, 8, 22);
System.out.println("BirthDate: " + birthDate);
System.out.println("Age: " + calculateAge(birthDate));
//BirthDate: 1980-08-22
//Age: 43 Years, 4 Months and 13 Days

Please note that the Age calculation will be different depending upon today’s date.

That’s it! You can copy the code and use. Thanks for reading!