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.
> 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#?
smilly - 10 May 2005 18:48 GMT
{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()
);
}
> Look at the DateTime.Subtract method, which will subtract two dates,
> returning a TimeSpan,
[quoted text clipped - 5 lines]
> > For example, a person with birthday of 1964/09/25.
> > How to compute his age with c#?
smilly - 10 May 2005 19:14 GMT
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
}
}
> {sample}
> private void button1_Click_1(object sender, System.EventArgs e)
[quoted text clipped - 20 lines]
> > > For example, a person with birthday of 1964/09/25.
> > > How to compute his age with c#?
int age =
DateTime.Now.Year - DateOfBirth.Year +
(DateTime.Now.DayOfYear < DateOfBirth.DayOfYear ? -1 : 0);
// e.g., if date of birth is Juy 4, 1976:
DateTime DateOfBirth = new DateTime(1976, 7, 4);
int age =
DateTime.Now.Year - DateOfBirth.Year +
(DateTime.Now.DayOfYear < DateOfBirth.DayOfYear ? -1 : 0);
From http://www.developmentnow.com/g/36_2005_5_0_0_517919/How-to-compute-age.ht
Notice a bug in my code
From http://www.developmentnow.com/g/36_2005_5_0_0_517919/How-to-compute-age.ht
Steve Gerrard - 29 Mar 2008 16:29 GMT
> Notice a bug in my code?
>
[quoted text clipped - 3 lines]
> Posted via DevelopmentNow.com Groups
> http://www.developmentnow.com
Two words: leap year. ;-)
how about:
DateTime DateOfBirth = new DateTime(1976, 7, 4);
DateTime ThisDay = DateTime.Now.Date;
DateTime Birthday = new DateTime(ThisDay.Year, DateOfBirth.Month,
DateOfBirth.Day);
int age =
ThisDay.Year - DateOfBirth.Year + (ThisDay < Birthday? -1 : 0);
Family Tree Mike - 29 Mar 2008 16:38 GMT
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.
> Notice a bug in my code?
>
> From http://www.developmentnow.com/g/36_2005_5_0_0_517919/How-to-compute-age.htm
>
> Posted via DevelopmentNow.com Groups
> http://www.developmentnow.com