Calculating age from datetime field including time span
本问题已经有最佳答案,请猛点这里访问。
我试着调用这个函数,它应该返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | DateTime myDate3test = Convert.ToDateTime("1958-10-17 13:45:59.473"); Console.WriteLine(CalculateAge(myDate3test)); //this should return 57 if run today October 18, 2016 since the person is not yet 58 public static string CalculateAge(DateTime dtDateOfBirth) { int age = 0; DateTime dtNow = DateTime.Now; string measurement = string.Empty; if (DateTime.Compare(dtNow, dtDateOfBirth) == 1) { TimeSpan tsAge = dtNow.Subtract(dtDateOfBirth); DateTime dtAge = new DateTime(tsAge.Ticks); var vNowDate = Convert.ToInt32(dtNow.ToString("yyyyMMdd")); var vBirthdate = Convert.ToInt32(dtDateOfBirth.ToString("yyyyMMdd")); double diff = (vNowDate - vBirthdate) / 10000; age = Convert.ToInt32(Math.Truncate(diff)); measurement =" year"; if (age == 0) // patient is not 1 year old yet { age = dtAge.Month - 1; measurement =" month"; if (age == 0) // patient is not 1 month old yet { age = dtAge.Day - 1; measurement =" day"; } } if (age > 1) { measurement +="s"; } } else { // Future date!!! measurement =" Unable to calculate age"; age = -1; } return age.ToString() + measurement; } |
感谢您的帮助。
你的输入是1958年10月17日,所以答案58年是正确的。http://www.calculator.net/age-calculator.html?今天=10%2F17%2F1958&ageat=10%2F18%2F1616&x=74&y=7