Given a DateTime representing a person’s birthday, how do I calculate their age in years?

Post author: Adam VanBuskirk
Adam VanBuskirk
6/3/23 in
Tech
C#

DateTime birthday = new DateTime(1990, 5, 10); // Example birthday

DateTime today = DateTime.Today;
int age = today.Year - birthday.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthday > today.AddYears(-age))
{
    age--;
}

Console.WriteLine($"The person is {age} years old.");

In the above code, we first create a DateTime object representing the person’s birthday (in this case, May 10th, 1990, as an example). Then, we get the current date using DateTime.Today. We calculate the difference between the current year and the birth year to determine the initial age.

Next, we compare the birthday’s month and day with the current month and day to check if the birthday has already occurred in the current year. If the birthday hasn’t occurred yet, we subtract one from the age. Finally, we output the calculated age. Note that this code assumes you’re using the Gregorian calendar.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC