0

Possible Duplicate:
How do I calculate someone's age in C#?

I am trying to create a form where a client's date of birth is entered and his age is displayed automatically in txtAge:

 private void Form3_Load(object sender, EventArgs e)
 {
     dtpDob.Value = DateTime.Today.Date;
     SqlConnection conn = new SqlConnection();
 }  

 private void dtpDOB_Leave(object sender, System.EventArgs e)
 {
     System.DateTime dob = default(System.DateTime);
     dob = dtpDob.Value.Date;
     txtAge.Text = DateTime.DateDiff(DateInterval.Year, dob, DateTime.Today.Date);
 }

But I get these errors:

'System.DateTime' does not contain a definition for 'DateDiff'.
The name 'DateInterval' does not exist in the current context.

Community
  • 1
  • 1

3 Answers3

6
public static int GetAge(DateTime birthDate)
        {
            return (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.242199);
        }
Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93
  • doing this as an extension method would be a nice way to do it too :) – stack72 Aug 13 '11 at 22:21
  • 1
    That doesn't account for leap years, so it will show the wrong age when the birthday is close to todays date. – Guffa Aug 13 '11 at 22:25
  • @Guffa true, added that part. Nonetheless this question should be closed due to duplicate – Oskar Kjellin Aug 13 '11 at 22:31
  • That's better, but it's still an approximation and shows the wrong age in some cases (Yes, I have tested this). – Guffa Aug 13 '11 at 22:43
  • @Guffa yaeh I know. Tested it myself. But didn't feel like putting too much time into a question when the answer is already in SO – Oskar Kjellin Aug 14 '11 at 11:24
  • @Oskar Kjellin: So why did you post an answer at all, if you are not bothered to post code that works properly? – Guffa Aug 14 '11 at 11:38
  • @Guffa At first I was dedicated to make a good answer. But then I found the dupe and just wanted this to close – Oskar Kjellin Aug 14 '11 at 11:46
1

You would need to import the VB libraries to use DateDiff, and it's not part of the DateTime structure.

Although, using DateDiff does not calculate the age correctly, it only gives you the difference between the years of the dates, not the difference between the dates in years.

A simple way to calculate the age is to increase the birth date by a year until you pass the todays date:

private void dtpDOB_Leave(object sender, System.EventArgs e) {
  System.DateTime dob = default(System.DateTime);
  dob = dtpDob.Value.Date;

  int age = -1;
  DateTime today = DateTime.Today;
  while (dob <= today) {
    age++;
    dob = dob.AddYears(1);
  }
  txtAge.Text = age.ToString();
}

Note: This calculation takes leap years into account, so you will get the actual age, not an approximation.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

try this for the age in days:

txtAgeInDays.Text = (DateTime.Now - dob).ToString ("dddddd");

see http://msdn.microsoft.com/en-us/library/system.timespan.tostring.aspx

Yahia
  • 69,653
  • 9
  • 115
  • 144