Given a DateTime
representing a person\'s birthday, how do I calculate their age in years?
This classic question is deserving of a Noda Time solution.
static int GetAge(LocalDate dateOfBirth)
{
Instant now = SystemClock.Instance.Now;
// The target time zone is important.
// It should align with the *current physical location* of the person
// you are talking about. When the whereabouts of that person are unknown,
// then you use the time zone of the person who is *asking* for the age.
// The time zone of birth is irrelevant!
DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];
LocalDate today = now.InZone(zone).Date;
Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);
return (int) period.Years;
}
Usage:
LocalDate dateOfBirth = new LocalDate(1976, 8, 27);
int age = GetAge(dateOfBirth);
You might also be interested in the following improvements:
Passing in the clock as an IClock
, instead of using SystemClock.Instance
, would improve testability.
The target time zone will likely change, so you'd want a DateTimeZone
parameter as well.
See also my blog post on this subject: Handling Birthdays, and Other Anniversaries