【发布时间】:2017-02-28 02:05:27
【问题描述】:
我正在尝试调用这个函数,它应该返回 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;
}
感谢任何帮助。
【问题讨论】:
-
嗨,Soner。我尝试了您提到的链接,但其中的代码在传递我传递的数据时也返回 58 DateTime myDate3test = Convert.ToDateTime("1958-10-17 13:45:59.473");
-
也许这对你有一些帮助。 stackoverflow.com/questions/9/…
-
感谢 Amey,Rafael 的回复,尝试了所有这些链接,但在通过这个日期时间 1958-10-17 13:45:59.473 时,我仍然得到 58 而不是 57 的答案