Java Calculate Age from LocalDate of Birth

Tags: Java LocalDate DateUtil

In this Java tutorial, we learn how to calculate someone’s age based on their birthday as a LocalDate value in Java programming language.

How to calculate age from LocalDate of birth in Java

A this step, we create a new Java class named DateUtil, in this new class create a new static method named getAge(LocalDate birthday), this method to calculate the number of age from a given LocalDate value and current system date then return age as an integer value.

DateUtil.java

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

public class DateUtil {

    /**
     * This method to calculate number of age from given birthday LocalDate value.
     * @param birthday the LocalDate of birth
     * @return number of age
     */
    public static int getAge(LocalDate birthday) {
        LocalDate today = LocalDate.now();
        int age = (int)ChronoUnit.YEARS.between(birthday, today);
        return age;
    }

}

In the following example Java code, we learn how to use the DateUtil class above to calculate age from given LocalDate object in Java program.

GetAgeFromLocalDateExample.java

import java.time.LocalDate;

public class GetAgeFromLocalDateExample {
    public static void main(String... args) {
        LocalDate birthday = LocalDate.of(1988, 7, 11);

        // Calculate Age from LocalDate of Birth
        int age = DateUtil.getAge(birthday);

        System.out.println("Today: " + LocalDate.now());
        System.out.println("LocalDate of birth: " + birthday);
        System.out.println("Age: " + age);
    }
}
The output as below.
Today: 2022-08-18
LocalDate of birth: 1988-07-11
Age: 34

Happy Coding 😊

Java Calculate Age from Date of Birth

Java Calculate Age from Calendar of Birth

Java Calculate Age from Instant of Birth

Java Calculate Age from LocalDateTime of Birth

Java Calculate Age from OffsetDateTime of Birth

Java Calculate Age from ZonedDateTime of Birth