age calculation

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.


public static int GetAge(DateTime birthDate)
        {
            return (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.242199);
        }

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.


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

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

上一篇: 计算C#WinForm中的活跃年数

下一篇: 年龄计算