从日期时间字段计算年龄,包括时间跨度

时间:2016-10-18 17:17:49

标签: c# datetime

我正在尝试调用此函数,该函数应返回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;
    }

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

相关问题