How to Calculate Age from Date of Birth in Java

To calculate age from the date of birth in Java, you should make use of the preferred java.time.LocalDate class from the new Date and Time API. But we will cover also the older java.util.Date class for legacy code.


Using java.time.LocalDate (Java 8 and above):

Example:
package org.code2care.examples;

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

public class CurrentAgeCalculator {

    public static void main(String[] args) {

        LocalDate dateOfBirth = LocalDate.of(1992, 12, 25);
        int age = calculateCurrentAge(dateOfBirth);
        System.out.println("Current Age is " + age);

    }

    public static int calculateCurrentAge(LocalDate dateOfBirth) {
        LocalDate currentDate = LocalDate.now();
        Period period = Period.between(dateOfBirth, currentDate);
        return period.getYears();
    }
}
Output:
Get Current Age from LocalDate in Java

Using java.util.Date (legacy):

Date currentDate = new Date();
long diff = currentDate.getTime() - dateOfBirth.getTime();
long ageInMilliseconds = diff;
int ageInYears = (int) (ageInMilliseconds / (365.25 * 24 * 60 * 60 * 1000));

As you may understand from this code, why Java 8 way is preferred and recommended.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!