从datetime字段计算年龄,包括时间跨度
本文关键字:包括 时间跨度 datetime 字段 计算 | 更新日期: 2023-09-27 18:13:30
我试图调用这个函数,它应该返回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;
}
您的输入是1958年10月17日所以58年的答案是正确的。http://www.calculator.net/age-calculator.html?today=10%2F17%2F1958& ageat = 10% 2 f18 % 2 f2016& x = 74, y = 7