snippetcsharpCritical
How do I calculate someone's age based on a DateTime type birthday?
Viewed 0 times
howdatetimecalculatebirthdaytypesomeoneagebased
Problem
Given a
DateTime representing a person's birthday, how do I calculate their age in years?Solution
An easy to understand and simple solution.
However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// If the birthdate hasn't arrived yet, subtract one year.
if (birthdate.Date > today.AddYears(-age)) age--;
However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.
Context
Stack Overflow Q#9, score: 2433
Revisions (0)
No revisions yet.