给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?


当前回答

我认为TimeSpan包含了我们所需要的一切,而不必求助于365.25(或任何其他近似值)。扩展Aug的示例:

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

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

其他回答

这里有一个单行线:

int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;

我已经创建了一个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;
    }
};

试试这个解决方案,它奏效了。

int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
           Int32.Parse(birthday.ToString("yyyyMMdd rawrrr"))) / 10000;

我只想这样做:

DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;

这样你就可以计算出一个人的确切年龄,如果你愿意的话,可以精确到毫秒。

非常简单的答案

        DateTime dob = new DateTime(1991, 3, 4); 
        DateTime now = DateTime.Now; 
        int dobDay = dob.Day, dobMonth = dob.Month; 
        int add = -1; 
        if (dobMonth < now.Month)
        {
            add = 0;
        }
        else if (dobMonth == now.Month)
        {
            if(dobDay <= now.Day)
            {
                add = 0;
            }
            else
            {
                add = -1;
            }
        }
        else
        {
            add = -1;
        } 
        int age = now.Year - dob.Year + add;