Java Calculate Age from Calendar of Birth

Tags: Java Calendar DateUtil

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

How to calculate age from Calendar of birth in Java

In this first step, we create a new Java class named DateUtil, and implement the static method named getAge(Calendar birthday), this method to calculate the number of age from a given Calendar object and current system Date as the following Java code.

DateUtil.java

import java.util.Calendar;

public class DateUtil {

    /**
     * This method to calculate number of age from given birthday Calendar value.
     * @param birthday the Calendar of birth
     * @return number of age
     */
    public static int getAge(Calendar birthday) {
        Calendar todayCalendar = Calendar.getInstance();
        int age = todayCalendar.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
        return age;
    }

}

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

GetAgeFromCalendarExample.java

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

public class GetAgeFromCalendarExample {
    public static void main(String... args) {
        Calendar birthday = new GregorianCalendar(1988, Calendar.JULY, 11);

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

        System.out.println("Today: " + new Date());
        System.out.println("Date of birth: " + birthday.getTime());
        System.out.println("Age: " + age);
    }
}
The output as below.
Today: Thu Aug 18 22:57:24 ICT 2022
Date of birth: Mon Jul 11 00:00:00 ICT 1988
Age: 34

Happy Coding 😊

Java Calculate Age from Date of Birth

Java Calculate Age from Instant of Birth

Java Calculate Age from LocalDate of Birth

Java Calculate Age from LocalDateTime of Birth

Java Calculate Age from OffsetDateTime of Birth

Java Calculate Age from ZonedDateTime of Birth