Here are some extension methods I frequently use when needing to calculate age. The first two extend TimeSpan to add a Years and TotalYears value to TimeSpan, the second extends a DateTime to give an Age (int) when passed a date to calculate the age from.

Code:

Namespace MyFunctions
static class MyExtensions
private const double YEAR_CALC = 365.2425;
public static int Years(this TimeSpan ts) {
return (int)Math.Floor(ts.TotalYears());
}
public static double TotalYears(this TimeSpan ts) {
return ((double)ts.Days) / YEAR_CALC;
}
public static int Age(this DateTime dob, DateTime fromDate) {
TimeSpan ts = fromDate.Subtract(dob);
int age = ts.Years();
//will never return negative years - if this is desired,
// just return age
return Math.Abs(age);
}
}
}

To use these, just add the following to the top of your class and the methods will be available on each of those types.

Code:

using MyFunctions.MyExtensions;