C# Program – How to Calculate Age based on DateTime ?


This content was proof-read by Grammarly. You can Try Grammary for FREE

In C#, you can calculate the age based on the datetime property by subtracting the number of years from today with the birthday year. We should also consider the Leap Year as needed.

How to Calculate age based on DateTime of Birthday in C# ?

Here’s a simple code snippet demonstrating how to do it.

using System;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            var birthday = new DateTime(1992, 10, 02);

            var age = DateTime.Today.Year - birthday.Year;

            if (birthday.Date > DateTime.Today.AddYears(-age)) age--;
            Console.WriteLine("Age = " + age);
            Console.ReadLine();
        }
    }
}

Output

%d bloggers like this: