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

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

    I use this:

    public static class DateTimeExtensions
    {
        public static int Age(this DateTime birthDate)
        {
            return Age(birthDate, DateTime.Now);
        }
    
        public static int Age(this DateTime birthDate, DateTime offsetDate)
        {
            int result=0;
            result = offsetDate.Year - birthDate.Year;
    
            if (offsetDate.DayOfYear < birthDate.DayOfYear)
            {
                  result--;
            }
    
            return result;
        }
    }
    

提交回复
热议问题