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:

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.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!