我正在尝试调用此函数,该函数应返回57
的年龄,但如果我今天在2016年10月18日运行它,则会返回58
。
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;
}
感谢任何帮助。
答案 0 :(得分:2)
您的输入是 1958-10-17所以答案58年是正确的。 http://www.calculator.net/age-calculator.html?today=10%2F17%2F1958&ageat=10%2F18%2F2016&x=74&y=7