如何计算c#中dob的年龄

时间:2013-02-08 05:10:54

标签: c# asp.net dob

   private void button1_Click(object sender, EventArgs e)
    {
        DateTime dob = new DateTime();
        textBox1.Text = dob.ToString();
        int age;
        age = Convert.ToInt32(textbox2.Text);
        age = DateTime.Now.Year - dob.Year;
        if (DateTime.Now.DayOfYear < dob.DayOfYear)
            age = age - 1;

    }

如何从dob计算年龄。这是我的form.c.cs.any的想法

3 个答案:

答案 0 :(得分:7)

您可以使用TimeSpan计算它,如:

DateTime dob = .....
DateTime Today = DateTime.Now;
TimeSpan ts = Today - dob;
DateTime Age = DateTime.MinValue + ts;


// note: MinValue is 1/1/1 so we have to subtract...
int Years = Age.Year - 1;
int Months = Age.Month - 1;
int Days = Age.Day - 1;

来源:http://forums.asp.net/t/1289294.aspx/1

答案 1 :(得分:7)

DateTime today = DateTime.Today;

int age = today.Year - bday.Year;

if (bday > today.AddYears(-age))
 age--;

答案 2 :(得分:0)

[更新]:要考虑闰年,请使用365.242 instead of 365。你应该很好till the year 2799 I believe

DateTime有一个运算符重载,当你使用减法运算符时,你得到一个TimeSpan实例。

所以你会这样做:

DateTime dob = ..
TimeSpan tm = DateTime.Now - dob;
int years = ((tm.Days)/365);

理想情况下,您的代码应如下所示:

private void button1_Click(object sender, EventArgs e)
{
    DateTime dob = //get this some somewhere..
    textBox1.Text = dob.ToString();
    TimeSpan tm = (DateTime.Now - dob);
    int age = (tm.Days/365) ;
}

TimeSpan结构代表一个时间间隔,它具有DaysHoursSeconds等属性,因此您可以根据需要使用它们。