How to calculate age in years from dob in c#

This question already has an answer here:

  • How do I calculate someone's age in C#? 64 answers

  • You can calculate it using TimeSpan like:

    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


    DateTime today = DateTime.Today;
    
    int age = today.Year - bday.Year;
    
    if (bday > today.AddYears(-age))
     age--;
    

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

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

    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 , Seconds etc so you could use them if you need.

    链接地址: http://www.djcxy.com/p/54350.html

    上一篇: 来自DateTime的年龄(出生日期)

    下一篇: 如何计算来自dob的年龄在c#中