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

后端 未结 30 2753
名媛妹妹
名媛妹妹 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:43

    I've made one small change to Mark Soen's answer: I've rewriten the third line so that the expression can be parsed a bit more easily.

    public int AgeInYears(DateTime bday)
    {
        DateTime now = DateTime.Today;
        int age = now.Year - bday.Year;            
        if (bday.AddYears(age) > now) 
            age--;
        return age;
    }
    

    I've also made it into a function for the sake of clarity.

提交回复
热议问题