Back to Blog
2 min read

How to Calculate Age in Java (LocalDate and Period Examples)

Learn how to calculate age from date of birth in Java with LocalDate and Period. Includes years completed, age as of a specific date, and common edge cases.

How to Calculate Age in Java (LocalDate and Period Examples)

How to Calculate Age in Java (LocalDate and Period Examples)

If you need to calculate age in Java, the safest starting point is LocalDate. For most apps, age means completed years, so the logic should check whether the birthday has already happened this year.

Quick option

If you want to verify a result first, use the online tool: Age Calculator Online.

Age in full years with LocalDate

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

public static int ageYears(LocalDate dob, LocalDate asOf) {
    return Period.between(dob, asOf).getYears();
}

int age = ageYears(LocalDate.of(1998, 10, 12), LocalDate.now());

Age as of a specific date

Many use cases need age on a reference date, not just today.

LocalDate dob = LocalDate.of(2000, 5, 9);
LocalDate asOf = LocalDate.of(2026, 3, 9);
int age = Period.between(dob, asOf).getYears();

Years, months, and days

If you need a fuller breakdown, Period can also return months and days.

Period p = Period.between(dob, asOf);
System.out.println(p.getYears());
System.out.println(p.getMonths());
System.out.println(p.getDays());

Common pitfalls

  • Use LocalDate, not Date: DOB is a calendar date, so avoid time zone noise when possible.
  • Validate future DOBs: reject inputs that create negative ages.
  • Test leap day birthdays: Feb 29 can matter in edge cases and business rules.

FAQ

Is Period.between good enough for age?

Yes, for most business cases. It gives completed years based on real calendar dates.

Should I use LocalDate or LocalDateTime?

Use LocalDate for date of birth unless you truly need a birth timestamp.

Related