How to calculate age from a birth date
Short answer
Period.between() from the birth date to today gives the number of full years. In the example "today" is fixed so the result is always the same:
void main() {
var birthday = LocalDate.of(1990, 7, 15);
var today = LocalDate.of(2026, 3, 8);
IO.println(Period.between(birthday, today).getYears());
}Output:
35In real code use LocalDate.now().
With ChronoUnit
ChronoUnit.YEARS.between() returns the same as a single number:
void main() {
var birthday = LocalDate.of(1990, 7, 15);
IO.println(ChronoUnit.YEARS.between(birthday, LocalDate.of(2026, 7, 14)));
IO.println(ChronoUnit.YEARS.between(birthday, LocalDate.of(2026, 7, 15)));
}Output:
35
36The full age
A Period also holds months and days:
void main() {
var age = Period.between(LocalDate.of(2024, 1, 20), LocalDate.of(2026, 3, 8));
IO.println(age.getYears() + " y " + age.getMonths() + " m " + age.getDays() + " d");
}Output:
2 y 1 m 16 dCommon mistake
Subtracting years: 2026 - 1990. If the birthday has not happened yet this year, the age comes out one year too high:
void main() {
var birthday = LocalDate.of(1990, 7, 15);
var today = LocalDate.of(2026, 3, 8);
IO.println(today.getYear() - birthday.getYear());
IO.println(Period.between(birthday, today).getYears());
}Output:
36
35Functions used in this recipe
- Period — A calendar amount in years, months and days — for example, an age.
- ChronoUnit.between() — Counts the whole units (days, months, hours) between two dates or moments.
- LocalDate.now() — Returns today's date from the computer's clock and time zone.