C# calculate accurate age

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

    If you have a Instance Variable/Property that names DateOfBirth, you can use this method. Otherwise, you can pass the Date of Birth as a parameter for method. I made some calculus and I proved that never fails.

    public int AgeCalc(){
          DateTime now = DateTime.Now;
          double age =  Math.Floor((DateTime.Now - DateOfBirth).TotalDays)/((DateTime.IsLeapYear(year: now.Year)? 366 : 365));
          return (age % 1) >= 0.951 ? Math.Round(age) : Math.Floor(age);
    }
    
    

    I hope that this can help you :)

提交回复
热议问题