How to calculate age in years from dob in c# [duplicate] How to calculate age in years from dob in c# [duplicate] asp.net asp.net

How to calculate age in years from dob in c# [duplicate]


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


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


[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.