gwenda wrote:
Hi Ansil - I like your answer but what if you want to report the age
in Years, Months, Days??
G
"Ansil MCAD" wrote:
Here's what I think you want ---
Bob
int age= Age(DateTime.Parse("4/26/1973"));
public static int Age(DateTime birthDate)
{
int years, months, days;
DateDiff(DateTime.Now, birthDate, out years, out months, out days);
return years;
}
public static void DateDiff(DateTime d1, DateTime d2,
out int years, out int months, out int days)
{
// compute & return the difference of two dates,
// returning years, months & days
// d1 should be the larger (newest) of the two dates
//
//
// y m d
// 3/10/2005 <-- 3/10/2005 0 0 0
// 3/10/2005 <-- 3/09/2005 0 0 1
// 3/10/2005 <-- 3/01/2005 0 0 9
// 3/10/2005 <-- 2/28/2005 0 0 10
// 3/10/2005 <-- 2/11/2005 0 0 27
// 3/10/2005 <-- 2/10/2005 0 1 0
// 3/10/2005 <-- 2/09/2005 0 1 1
// 3/10/2005 <-- 7/20/1969 35 7 21
// we want d1 to be the larger (newest) date
// flip if we need to
if (d1 < d2)
{
DateTime d3= d2;
d2= d1;
d1= d3;
}
// compute difference in total months
months= 12 * (d1.Year - d2.Year) + (d1.Month - d2.Month);
// based upon the 'days',
// adjust months & compute actual days difference
if (d1.Day < d2.Day)
{
months--;
days= GetDaysInMonth(d2.Year, d2.Month) - d2.Day + d1.Day;
}
else
{
days= d1.Day - d2.Day;
}
// compute years & actual months
years= months / 12;
months-= years * 12;
//Debug.WriteLine(string.Format("{0} <-- {1} {2,2} {3,2} {4,2}",
d1.ToShortDateString(),d2.ToShortDateString(),year s,months,days));
}
private static int GetDaysInMonth(int year, int month)
{
// this is also available from Calendar class,
// but just as easy to do ourselves
if (month < 1 || month > 12)
{
throw new ArgumentException("month value must be from 1-12");
}
// 1 2 3 4 5 6 7 8 9 10 11 12
int[] days= {0, 31,28,31,30,31,30,31,31,30,31,30,31};
if (((year/400*400) == year) ||
(((year/4*4)==year) && (year%100 != 0)))
{
days[2]= 29;
}
return days[month];
}