How to compute age

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

How to compute the age of a person?
For example, a person with birthday of 1964/09/25.
How to compute his age with c#?
 
simply substract two DataTime values, u will get TimeSpan object. then u can
convert it to a suitable string
 
Look at the DateTime.Subtract method, which will subtract two dates,
returning a TimeSpan,
which will tell you the number of years the two dates are apart. One of
your DateTimes would be
DateTime.Now, the other the date of the person's birth.
 
{sample}
private void button1_Click_1(object sender, System.EventArgs e)
{
DateTime d1=DateTime.Now;
DateTime d2=DateTime.Now;
try
{
d2=Convert.ToDateTime(textBox1.Text);
}
catch (Exception){}
MessageBox.Show(
"Your age is "+(d1.Year-d2.Year).ToString()
);
}
 
sorry about the previous post ;-)


using System;

namespace CommonLib
{
public class DateRoutines
{
#region Methods

public static int GetAge(DateTime aBirthDate)
{
TimeSpan span=DateTime.Now.Subtract(aBirthDate);
return span.Days/365;
}

#endregion Methods
}
}
 
If your timing was great, the two different uses of DateTime.Now could be on
different dates. Only problematic I believe, if the second one is the
birthday date.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top