Calculate age with DateOnly and a stated leap-day rule

Calculate age in completed years by comparing a date of birth with an explicit assessment date. Subtracting the years alone is insufficient when the birthday has not occurred yet. Dividing elapsed days by 365 or 365.25 also substitutes an average duration for a calendar rule.

Use DateOnly when the inputs represent dates rather than instants. Then state how a 29 February birthday is treated in a non-leap year. The example supports either 28 February or 1 March as the anniversary. The caller chooses the convention required by its application. This article does not prescribe a legal eligibility rule.

Implement the anniversary rule

Create a .NET 10 console project with dotnet new console -n AgeDemo -f net10.0. Replace Program.cs and run dotnet run --project AgeDemo from its parent directory.

C#
using System;

var birthday = new DateOnly(2000, 6, 15);
Console.WriteLine(CalculateAge(birthday, new DateOnly(2026, 6, 14), LeapDayRule.February28));
Console.WriteLine(CalculateAge(birthday, new DateOnly(2026, 6, 15), LeapDayRule.February28));
var leapBirthday = new DateOnly(2024, 2, 29);
foreach (var rule in Enum.GetValues<LeapDayRule>()) {
	Console.WriteLine($"{rule} on Feb 28={CalculateAge(leapBirthday, new DateOnly(2025, 2, 28), rule)}");
	Console.WriteLine($"{rule} on Mar 1={CalculateAge(leapBirthday, new DateOnly(2025, 3, 1), rule)}");
}

try {
	CalculateAge(birthday, new DateOnly(1999, 12, 31), LeapDayRule.February28);
} catch (ArgumentOutOfRangeException) {
	Console.WriteLine("Rejected future birth date");
}

static int CalculateAge(DateOnly birthDate, DateOnly asOf, LeapDayRule leapDayRule) {
	if (birthDate > asOf) {
		throw new ArgumentOutOfRangeException(nameof(birthDate), "Birth date is after the assessment date.");
	}
	if (!Enum.IsDefined(leapDayRule)) {
		throw new ArgumentOutOfRangeException(nameof(leapDayRule));
	}
	var years = asOf.Year - birthDate.Year;
	DateOnly anniversary;
	if (birthDate.Month == 2 && birthDate.Day == 29 && !DateTime.IsLeapYear(asOf.Year)) {
		anniversary = leapDayRule == LeapDayRule.February28
			? new DateOnly(asOf.Year, 2, 28)
			: new DateOnly(asOf.Year, 3, 1);
	} else {
		anniversary = new DateOnly(asOf.Year, birthDate.Month, birthDate.Day);
	}
	return asOf < anniversary ? years - 1 : years;
}

enum LeapDayRule {
	February28,
	March1
}

Expected output:

Plain text
25
26
February28 on Feb 28=1
February28 on Mar 1=1
March1 on Feb 28=0
March1 on Mar 1=1
Rejected future birth date

The function first validates its inputs. It builds this year's anniversary, then subtracts one year if that date is still in the future. It does not mutate either input and does not depend on the machine clock.

Select the date before calculating

When the rule means “age today,” obtain today's date in the relevant business time zone before calling the function. A server's local date and the user's local date can differ near midnight. Passing asOf explicitly makes the result reproducible in tests, reports and historical evaluations.

If a birth date arrives as text, parse it according to a defined input format or user culture. Avoid guessing whether 03/04/2000 means March or April. For an API that specifies ISO dates, require its stated year-month-day representation and report invalid dates separately from age calculation.

Test the calendar boundaries

Test the day before a birthday, the birthday itself and the day after. Include a leap-year anniversary on 29 February and both non-leap conventions. Also test a birth date equal to the assessment date, a future birth date and an invalid enum value supplied by a caller.

DateOnly uses the proleptic Gregorian calendar for its stored dates. If your domain uses another calendar, historical jurisdiction-specific rules or an exact time of birth, define that requirement before adapting this function. Those requirements change the input model or anniversary rule rather than the arithmetic syntax.

For many ordinary birthdays, birthDate.AddYears(years) is a convenient anniversary calculation. The explicit branch here makes the exceptional policy visible and prevents an implicit leap-day adjustment from becoming an accidental business decision.

References

How to use DateOnly and TimeOnly - .NET
Learn about the DateOnly and TimeOnly structures in .NET.
https://learn.microsoft.com/en-us/dotnet/standard/datetime/how-to-use-dateonly-timeonly
DateOnly.AddYears(Int32) Method (System)
Adds the specified number of years to the value of this instance.
https://learn.microsoft.com/en-us/dotnet/api/system.dateonly.addyears?view=net-10.0
DateTime.IsLeapYear(Int32) Method (System)
Returns an indication whether the specified year is a leap year.
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.isleapyear?view=net-10.0

Question provenance

This article addresses How do I calculate someone's age based on a DateTime type birthday? , asked by Jeff Atwood on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.

Author: Herman Schoenfeld