In C#, how do I calculate someone's age based on a DateTime type birthday?

后端 未结 30 2216
名媛妹妹
名媛妹妹 2020-11-21 05:14

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

30条回答
  •  春和景丽
    2020-11-21 05:51

    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 in which 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 the age and not using East Asian reckoning.

提交回复
热议问题