Click to See Complete Forum and Search --> : Calculating Age


Aaron Fanetti
March 27th, 2001, 06:16 PM
This has been re-posted from another list, so sorry if you're seeing it twice.

I am having trouble with DateTime and TimeSpan classes. I need a function
that calculates the number of Years (integral value) between two dates.
The TimeSpan looked promising, but alas the largest unit returned is days.

Int32 AgeInYears( DateTime startDate, DateTime endDate )
{
/* Help, ugh! */
}

Just to be safe, targetDate1.Year - startDate.Year is not sufficient as it
is not the difference in between the nominal years I am interested in. Rather, I want to get
at the number of years in the span between the target and the start. Also,
just using the TimeSpan.Day and assuming that 365 days = 1 year does not work
either as leap years would be ignored, etc.


TIA!
Aaron

Martin Perkins
April 4th, 2001, 10:18 AM
This should help you. Calculates the age from today, needs a small change for your requirement
DateTime dTodaysDate = DateTime.Today;
int nToday = dTodaysDate.Year * 10000 + dTodaysDate.Month * 100 + dTodaysDate.Day;
int nBirth = m_dBirthDate.Year * 10000 + m_dBirthDate.Month * 100 + m_dBirthDate.Day;
int nAge = (nToday - nBirth) / 10000;