Friday, 7 July 2017

Calculate age in C#

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

Solution:


// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year the person was born in case of a leap year
if (birthdate > today.AddYears(-age)) age--;

No comments:

Post a Comment