如何从c#中的dob计算年龄(以年为单位)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14766086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:56:21  来源:igfitidea点击:

How to calculate age in years from dob in c#

c#asp.netdob

提问by Dilipan K

   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;

    }

How to claculate the age from dob.This is my form1.cs.any ideas please

如何从 dob 中算出年龄。这是我的 form1.cs.any 想法请

采纳答案by Habib

You can calculate it using TimeSpan like:

您可以使用 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;

Source: http://forums.asp.net/t/1289294.aspx/1

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

回答by gideon

[Update]:To account for leap years use 365.242 instead of 365. You should be good till the year 2799 I believe.

[更新]:为了说明闰年,请使用365.242 而不是 365我相信你应该一直保持到 2799 年

DateTime has an operator overload, when you use the subtract operator you get a TimeSpaninstance.

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

So you will just do:

所以你只会做:

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

Your code should ideally look like this:

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

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) ;
}

The TimeSpan structure represents a time interval, it has properties like Days,Hours,Secondsetc so you could use them if you need.

时间跨度结构代表的时间间隔,它具有像性能DaysHoursSeconds等因此,如果你需要,你可以使用它们。

回答by VasanthRavichandran

DateTime today = DateTime.Today;

int age = today.Year - bday.Year;

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