Calculate Exact Age from Date of Birth in Java
Problem
An exact age is the calendar difference between the birth date and today, expressed as completed years, months and remaining days.
Given a date of birth and today's date, print the exact age and the date of the next birthday.
Java Program
import java.time.LocalDate;
import java.time.Period;
public class ExactAgeFromBirthDate {
public static void main(String[] args) {
LocalDate birth = LocalDate.of(1998, 11, 23);
LocalDate today = LocalDate.of(2026, 10, 12); // fixed "today" so the result never changes
Period age = Period.between(birth, today);
System.out.println("Age: " + age.getYears() + " years, " + age.getMonths() + " months, " + age.getDays() + " days");
LocalDate nextBirthday = birth.withYear(today.getYear());
if (!nextBirthday.isAfter(today)) nextBirthday = nextBirthday.plusYears(1);
System.out.println("Next birthday: " + nextBirthday);
}
}Output
Core Logic
Period.between follows the real calendar, so it handles month lengths and leap years that simple subtraction gets wrong.
- 1Both dates are fixed with
LocalDate.of, so the result is the same on every run. - 2
Period.between(birth, today)returns years, months and days. - 3
birth.withYear(today.getYear())gives this year's birthday. - 4If that date has already passed (or is today), one year is added to get the next birthday.
Key Point: Subtracting birth year from current year overcounts by one until this year's birthday — Period avoids that.
Key Concepts
Approach 2: Completed Years and Total Days
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class ExactAgeChronoUnit {
public static void main(String[] args) {
LocalDate birth = LocalDate.of(1998, 11, 23);
LocalDate today = LocalDate.of(2026, 10, 12);
long years = ChronoUnit.YEARS.between(birth, today); // whole completed years only
long days = ChronoUnit.DAYS.between(birth, today);
System.out.println("Completed years: " + years);
System.out.println("Days alive: " + days);
System.out.println("Is an adult (18+): " + (years >= 18));
}
}
Output
Core Logic
When you need one number — such as completed years for an age check — ChronoUnit gives it directly.
- 1
ChronoUnit.YEARS.betweencounts only fully completed years. - 2
ChronoUnit.DAYS.betweencounts the total days. - 3The adult check compares completed years with 18.
Key Point: Period.getDays() is only the leftover days; use ChronoUnit.DAYS for the total.
Key Concepts
Interview Questions
How do you handle someone born on 29 February?
withYear moves 29 February to 28 February in non-leap years, which is the usual legal convention; check your requirements in case 1 March is expected.
Why use a fixed "today" in tests?
LocalDate.now() changes every day, so tests would break. Pass the date in, or use a Clock that can be fixed in tests.