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

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

    private int GetAge(int _year, int _month, int _day
    {
        DateTime yourBirthDate= new DateTime(_year, _month, _day);
    
        DateTime todaysDateTime = DateTime.Today;
        int noOfYears = todaysDateTime.Year - yourBirthDate.Year;
    
        if (DateTime.Now.Month < yourBirthDate.Month ||
            (DateTime.Now.Month == yourBirthDate.Month && DateTime.Now.Day < yourBirthDate.Day))
        {
            noOfYears--;
        }
    
        return  noOfYears;
    }
    

提交回复
热议问题