A quick a dirty way to get someones age in months or the difference in months between two dates is to subtract the dates from each other to get the number of days and divide the result by 30.
(to_date – from_date) / 30 = AgeInMonths
The issue with this is that not all months are 30 days long and usually we calculate a month as something like this: 1/10/2011 to 1/09/2011. In that example a new month will always start on the 10th. Below is a C# method that will calculate months using this method.
UPDATE: I updated the method to include and argument that asks if you want the month counting at 0 or 1. That argument is a bool called firstMonthZero and defaults to true. When true, the first month will be month 0 and when set to false, the first month will be month 1.
public static int GetAgeInMonths(DateTime date1, DateTime date2, bool firstMonthZero = true)
{
//firstMonthZero: If set to True, the first month is Month Zero. If false the first month is month 1
int year1 = date1.Year;
int year2 = date2.Year;
int month1 = date1.Month;
int month2 = date2.Month;
int day1 = date1.Day;
int day2 = date2.Day;
int tempMonths = 0;
int ageMonths = 0;
if (date2 < date1)
{
ageMonths = -1;
}
else if (year1 == year2)
{
tempMonths = month2 - month1;
if (tempMonths == 0)
{
ageMonths = tempMonths;
}
else
{
if (day2 < day1)
{
ageMonths = tempMonths - 1;
}
else
{
ageMonths = tempMonths;
}
}
}
else
{
//count months in year 1
int year1MonthCount = 0;
int year2MonthCount = 0;
int inBetweenYearsMonthCount = ((year2 - year1) - 1) * 12;
if (inBetweenYearsMonthCount < 0)
{
inBetweenYearsMonthCount = 0;
}
year1MonthCount = (12 - month1);
year2MonthCount = month2;
ageMonths = year1MonthCount + inBetweenYearsMonthCount + year2MonthCount;
//If Date2's day is less than Date 1's day, subtract a month.
//e.g. 1/10/2011 to 1/9/2012 is still twelve months because date 2 hasnt reached the 10th of the month
//e.g. 1/10/2011 to 1/10/2012 is still thirteen months because date 2 has reached the 10th of the month
if (day2 < day1)
{
ageMonths -= 1;
}
}
if (ageMonths == -1)
{
return ageMonths;
}
else if (firstMonthZero)
{
return ageMonths;
}
else
{
return ageMonths + 1;
}
}