I'm trying to call this function which should return the age of 57
but is returning 58
if I run it today October 18, 2016.
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;
}
Any help is appreciated.