Java Calculate Age from LocalDateTime of Birth

Tags: Java LocalDateTime DateUtil

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

How to calculate age from LocalDateTime of birth in Java

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

DateUtil.java

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class DateUtil {

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

}

In this following example Java code, we learn how to use the DateUtil class above to calculate number of age from given LocalDateTime value in Java program.

GetAgeFromLocalDateTimeExample.java

import java.time.LocalDateTime;

public class GetAgeFromLocalDateTimeExample {
    public static void main(String... args) {
        LocalDateTime birthday = LocalDateTime.of(1988, 7, 11, 0, 0, 0);

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

        System.out.println("Today: " + LocalDateTime.now());
        System.out.println("LocalDateTime of birth: " + birthday);
        System.out.println("Age: " + age);
    }
}
The output as below.
Today: 2022-08-18T23:53:29.223557900
LocalDateTime of birth: 1988-07-11T00:00
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 LocalDate of Birth

Java Calculate Age from OffsetDateTime of Birth

Java Calculate Age from ZonedDateTime of Birth