Calculate Age From Date Of Birth (DateTime Birthdate) In C#

Sameer Saini May 31, 2022
Calculate Age From Date Of Birth (DateTime Birthdate) In C#

In this blog post, we will learn how we can calculate the age of a person from their birthdate (birthday) in C#.

To calculate the age of the person as of today's date, we need two variables, today's date and the birthdate(birth date) of the person for which we want to calculate the age.

To calculate the age of the person, we will use the .Subtract() method available on the DateTime object.

Using this, we calculate the difference between the two dates and then calculate the age in years, months, days etc.

 

 

 

 

Calculate Age Of Person In C# Using .Subtract() Method

We can make use of the .Subtract() method that is available on the Datetime object.

Using the Subtract(DateTime) overload of this method, we will use the subtract method on today's date (DateTime.Now) and then subtract the birthdate from it.

This will give us a Timespan from which we can calculate the age in Years, Months, Days etc.

Let's see this in an example.

 

Example:

namespace ConsoleApp { public class Program { public static void Main() { DateTime dateTimeToday = DateTime.UtcNow; DateTime birthDate = new DateTime(1956, 8, 27); TimeSpan difference = dateTimeToday.Subtract(birthDate); var firstDay = new DateTime(1, 1, 1); Console.WriteLine($"Age in seconds: {Math.Round(difference.TotalSeconds)}"); Console.WriteLine($"Age in minutes: {Math.Round(difference.TotalMinutes)}"); Console.WriteLine($"Age in hours: {Math.Round(difference.TotalHours)}"); Console.WriteLine($"Age in days: {Math.Round(difference.TotalDays)}"); Console.WriteLine($"Age in weeks: {System.Math.Ceiling(difference.TotalDays / 7)}"); int totalYears = (firstDay + difference).Year - 1; Console.WriteLine($"Age in years: {totalYears}"); int totalMonths = (totalYears * 12) + (firstDay + difference).Month - 1; Console.WriteLine($"Age in months: {totalMonths}"); int runningMonths = totalMonths - (totalYears * 12); Console.WriteLine($"Age in {runningMonths}"); int runningDays = (dateTimeToday - birthDate.AddMonths((totalYears * 12) + runningMonths)).Days; Console.WriteLine($"Age in {runningDays}"); Console.WriteLine($"Age is {totalYears} years, {runningMonths} months, {runningDays} days"); } } }

 

Result:

Age in seconds: 2075162838 Age in minutes: 34586047 Age in hours: 576434 Age in days: 24018 Age in weeks: 3432 Age in years: 65 Age in months: 789 Age in 9 Age in 4 Age is 65 years, 9 months, 4 days