C# calculate accurate age

前端 未结 14 1753
攒了一身酷
攒了一身酷 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:58

    This sounds like a fine exercise to get to know the TimeSpan class better.

    0 讨论(0)
  • 2020-12-15 11:59

    Since i can't post code to a comment, here it is the code based on @LukeH answer, with the bug fixed

    public static int GetAge( DateTime dob, DateTime today, out int days, out int months ) {
            DateTime dt = today;
            if( dt.Day < dob.Day ) {
                dt = dt.AddMonths( -1 );
            }
    
            months = dt.Month - dob.Month;
            if( months < 0 ) {
                dt = dt.AddYears( -1 );
                months += 12;
            }
    
            int years = dt.Year - dob.Year;
            var offs = dob.AddMonths( years * 12 + months );
            days = (int)( ( today.Ticks - offs.Ticks ) / TimeSpan.TicksPerDay );
            return years;
        }
    
    0 讨论(0)
提交回复
热议问题