How to Calculate Age in C# (DateOnly, DateTime, and Birthday Logic Examples)
Learn how to calculate age from date of birth in C#: a simple DateOnly approach, a DateTime version, and birthday logic that handles edge cases cleanly.
How to Calculate Age in C# (DateOnly, DateTime, and Birthday Logic Examples)
Age calculation in C# is mostly about one rule: subtract the birth year, then reduce by one if the birthday has not happened yet this year. The examples below focus on completed years, which is what most apps need.
Fast option: use an online age calculator
If you want a quick answer or a test baseline for your code, use an online tool first. It is handy for checking tricky dates like leap years and birthdays near month boundaries.
Open the age calculator and enter the date of birth plus any reference date.
Best modern option: DateOnly
DateOnly keeps the problem date-based, which avoids time-of-day noise.
public static int AgeYears(DateOnly birthDate, DateOnly asOf)
{
int years = asOf.Year - birthDate.Year;
if (asOf < birthDate.AddYears(years))
years--;
return years;
}
var age = AgeYears(new DateOnly(1998, 10, 12), DateOnly.FromDateTime(DateTime.Today));
DateTime version
If your project still uses DateTime, compare only the date parts.
public static int AgeYears(DateTime birthDate, DateTime asOf)
{
int years = asOf.Year - birthDate.Year;
if (asOf.Date < birthDate.Date.AddYears(years))
years--;
return years;
}
Why this logic works
Someone turns a new age only when their birthday arrives. If the reference date is still before that birthday in the current year, the age must be one year lower.
Leap year note
For February 29 birthdays, different businesses may use February 28 or March 1 in non-leap years. .NET date math helps, but you should still confirm the rule your app needs.
FAQ
Should I use DateOnly or DateTime?
If you only care about age from date of birth, DateOnly is usually cleaner and safer.
How do I calculate exact age in years, months, and days?
That needs extra unit-by-unit logic. For validation and quick checks, an age calculator is a useful reference.