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.

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap