14
   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

leppie
  • 115,091
  • 17
  • 196
  • 297
Dilipan K
  • 151
  • 1
  • 2
  • 6

3 Answers3

10
DateTime today = DateTime.Today;

int age = today.Year - bday.Year;

if (bday > today.AddYears(-age))
 age--;
Ankur
  • 5,086
  • 19
  • 37
  • 62
8

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

Habib
  • 219,104
  • 29
  • 407
  • 436
  • In my testing there are certain dates which this produces incorrect results for :( E.g., try calculating somebody's age on 2017-01-12 when that person was born on 1996-01-13. The above code returns an age of 21 instead of 20, however their 21st birthday should be tomorrow. – lethek Jan 12 '17 at 00:37
0

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

gideon
  • 19,329
  • 11
  • 72
  • 113