How to calculate age in years from dob in c# [duplicate]
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;
[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.