Back to Blog
2 min read

How to Calculate Age in C# (DateTime and DateOnly Examples)

Learn how to calculate age from date of birth in C#. Includes years completed, age as of a specific date, DateOnly examples, and common edge cases.

How to Calculate Age in C# (DateTime and DateOnly Examples)

How to Calculate Age in C# (DateTime and DateOnly Examples)

If you need to calculate age in C#, the key detail is using completed years. Simple year subtraction is wrong before the birthday. This guide shows a safe pattern for both DateTime and DateOnly.

1) Calculate age in full years

This pattern subtracts one year if the birthday has not happened yet in the current year.

using System;

public static int AgeYears(DateOnly dob, DateOnly? asOf = null)
{
    var today = asOf ?? DateOnly.FromDateTime(DateTime.UtcNow);
    int years = today.Year - dob.Year;
    if (today < dob.AddYears(years)) years--;
    return years;
}

var age = AgeYears(new DateOnly(1998, 10, 12), new DateOnly(2026, 3, 12));

2) Using DateTime

If your app still stores DOB as DateTime, convert to a date first when possible. DOB is usually a calendar date, not a timestamp.

using System;

public static int AgeYears(DateTime dob, DateTime? asOf = null)
{
    var today = (asOf ?? DateTime.UtcNow).Date;
    dob = dob.Date;
    int years = today.Year - dob.Year;
    if (today < dob.AddYears(years)) years--;
    return years;
}

3) Age as of a specific date

Many business rules need age on a cutoff date, not just today. The examples above support that directly via asOf.

4) Common pitfalls

  • Birthday not reached yet: plain today.Year - dob.Year overstates age.
  • Time zones: use a consistent date basis like UTC or local business time.
  • Leap day birthdays: confirm how your app should treat Feb 29 in non leap years.

Quick check

If you want to verify a DOB fast, use the online calculator: Calculate Age Online.

Related guides

FAQ

Is DateOnly better than DateTime for date of birth?

Usually yes. DOB is normally a calendar date, so DateOnly avoids unnecessary time and time zone issues.

Why is AddYears useful here?

It lets you compare the current date with the birthday in the current year, which is the cleanest way to check whether the birthday has already happened.