Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Month diff calculator
public static class DateTimeExtensionMethods
{
public static int GetMonthsDiff(this DateTime fromDate, DateTime toDate)
{
if (fromDate > toDate)
{
var aux = fromDate;
fromDate = toDate;
toDate = aux;
}
var monthDiff = (toDate.Year - fromDate.Year) * 12 + (toDate.Month - fromDate.Month);
var fromTimeIsLaterThanToTime = fromDate.AddMonths(monthDiff) > toDate;
if (fromTimeIsLaterThanToTime || !IsFullMonthDiff(fromDate, toDate))
{
monthDiff--;
}
return monthDiff;
}
public static bool IsLastDayOfMonth(this DateTime date)
{
return DateTime.DaysInMonth(date.Year, date.Month) == date.Day;
}
private static bool IsFullMonthDiff(DateTime fromDate, DateTime toDate)
{
return toDate.Day >= fromDate.Day || (toDate.IsLastDayOfMonth() && fromDate.IsLastDayOfMonth());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.