在C#中,如何计算年龄?

在C#中, 生日以DateTime的形式给定,如何计算他现在的年龄?

解决方案:

因为闰年,我们可以365.25作为一年粗略计算:

DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);

我认为TimeSpan包含了我们所需的全部内容,而不必求助于365.25(或者任何其他近似值)。

DateTime myBD = new DateTime(1980, 10, 10);
TimeSpan difference = DateTime.Now.Subtract(myBD);

textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";

我创建了一个SQL Server用户定义函数来计算某人的年龄(给定生日)。当我们需要将其作为查询的一部分时,这很有用:

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlInt32 CalculateAge(string strBirthDate)
    {
        DateTime dtBirthDate = new DateTime();
        dtBirthDate = Convert.ToDateTime(strBirthDate);
        DateTime dtToday = DateTime.Now;

        //get the difference in years
        int years = dtToday.Year - dtBirthDate.Year;

        //subtract another year if we're before the
        //birth day in the current year
        if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))
            years=years-1;

        int intCustomerAge = years;
        return intCustomerAge;
    }
};

这个是网上找到的方法:

public static int GetAge(DateTime birthDate)
{
    DateTime n = DateTime.Now; //To avoid a race condition around midnight
    int age = n.Year - birthDate.Year;

    if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
        age--;

    return age;
}
日期:2020-03-23 10:07:29 来源:oir作者:oir