Saturday, 14 January 2017

.net - How do I calculate someone's age in C#?



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


Answer



An easy to understand and simple 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.Date > today.AddYears(-age)) age--;


However, this assumes you are looking for the western idea of age and not using East Asian reckoning.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...