C# calculate accurate age

前端 未结 14 1801
攒了一身酷
攒了一身酷 2020-12-15 11:01

anyone know how to get the age based on a date(birthdate)

im thinking of something like this

string age = DateTime.Now.GetAccurateAge();
14条回答
  •  无人及你
    2020-12-15 11:45

    public static class DateTimeExtensions
    {
        public static string ToAgeString(this DateTime dob)
        {
            DateTime today = DateTime.Today;
    
            int months = today.Month - dob.Month;
            int years = today.Year - dob.Year;
    
            if (today.Day < dob.Day)
            {
                months--;
            }
    
            if (months < 0)
            {
                years--;
                months += 12;
            }
    
            int days = (today - dob.AddMonths((years * 12) + months)).Days;
    
            return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                                 years, (years == 1) ? "" : "s",
                                 months, (months == 1) ? "" : "s",
                                 days, (days == 1) ? "" : "s");
        }
    }
    

提交回复
热议问题