Last active
July 24, 2020 16:42
-
-
Save cristi-badila/5c3b92e420126ed2922c to your computer and use it in GitHub Desktop.
Month diff calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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