Skip to content

Instantly share code, notes, and snippets.

@cristi-badila
Last active July 24, 2020 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cristi-badila/5c3b92e420126ed2922c to your computer and use it in GitHub Desktop.
Save cristi-badila/5c3b92e420126ed2922c to your computer and use it in GitHub Desktop.
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