Skip to content

Instantly share code, notes, and snippets.

@M-Yankov
Last active June 30, 2017 13:55
Show Gist options
  • Save M-Yankov/62c4569ef36e23752fe88706b3f7cf03 to your computer and use it in GitHub Desktop.
Save M-Yankov/62c4569ef36e23752fe88706b3f7cf03 to your computer and use it in GitHub Desktop.
Calculate months between two dates.
private int GetMonthsBetweenTwoDates(DateTime startDate, DateTime endDate)
{
int monthsCountResult = 0;
var monthsCount = 12;
if (startDate.Year == endDate.Year)
{
monthsCountResult = (endDate.Month - startDate.Month) + 1;
}
else
{
int monthsStartDate = (monthsCount - startDate.Month) + 1;
int monthsEndDate = endDate.Month;
int middleYearsMonths = ((endDate.Year - startDate.Year) - 1) * monthsCount;
monthsCountResult = monthsStartDate + monthsEndDate + middleYearsMonths;
}
return monthsCountResult;
}
// Or
/*private int GetMonthsBetweenTwoDates(DateTime startDate, DateTime endDate)
{
endDate.Substract(startDate).Days / 30;
}*/
protected virtual int GetMonthsBetweenTwoDates(DateTime startDate, DateTime endDate, bool inclusive = true)
{
if (endDate.Year == startDate.Year && endDate.Month == startDate.Month)
{
// Because the logic for Jan 2016 - Jan 2016 returns 2
return 1;
}
// int theMonths = (endDate.Subtract(startDate).Days / 30) + 1;
int theMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
if (inclusive)
{
theMonths++;
}
return theMonths;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment