How would you calculate a person's age or the number of days until a recurring annual event (like a birthday) using ChronoUnit, and what's a common pitfall with leap-year birthdays (February 29)?
Short answer
ChronoUnit.YEARS.between(startDate, endDate) (or the more idiomatic Period.between() for calendar-based differences) computes a precise, calendar-aware age; a well-known edge case is a birthday falling on February 29 (a leap day), which doesn't exist in non-leap years --…
Advertisement
AModel answer
ChronoUnit.YEARS.between(startDate, endDate) (or the more idiomatic Period.between() for calendar-based differences) computes a precise, calendar-aware age; a well-known edge case is a birthday falling on February 29 (a leap day), which doesn't exist in non-leap years -- different applications handle this differently (commonly treating either February 28 or March 1 as the observed birthday in non-leap years), and this business decision needs to be made explicitly and consistently rather than left to an unexamined default behavior of whatever date arithmetic happens to produce.
LocalDate birthDate = LocalDate.of(2000, 2, 29); // a leap-day birthday
LocalDate nonLeapYear = LocalDate.of(2023, 1, 1); // 2023 is NOT a leap year
long age = ChronoUnit.YEARS.between(birthDate, LocalDate.now());
// Handling the Feb 29 edge case explicitly for a non-leap year
LocalDate thisYearsBirthday = birthDate.withYear(2023).isLeapYear()
? birthDate.withYear(2023)
: LocalDate.of(2023, 2, 28); // or March 1, depending on the business's chosen conventionReal-world example
A subscription renewal system explicitly decides and documents that a February 29 signup anniversary is treated as February 28 in non-leap years (rather than March 1, an equally valid alternative choice some other systems make), avoiding inconsistent or undefined behavior for the roughly 1-in-1461 users whose signup date happens to be a leap day.
Likely follow-ups
- What determines whether a given year is a leap year, and how does LocalDate.isLeapYear() implement this check?
- How would ChronoUnit.DAYS.between() behave differently from Period.between().getDays() for computing a difference spanning multiple months?
Related topics