Someone must have done it))
The extension method returns the number of full months between the given dates. No matter in what order the dates are received, a natural number will always be returned.No approximate calculations as in the "correct" answer.
/// <summary> /// Returns the difference between dates in months. /// </summary> /// <param name="current">First considered date.</param> /// <param name="another">Second considered date.</param> /// <returns>The number of full months between the given dates.</returns> public static int DifferenceInMonths(this DateTime current, DateTime another) { DateTime previous, next; if (current > another) { previous = another; next = current; } else { previous = current; next = another; } return (next.Year - previous.Year) * 12 // multiply the difference in years by 12 months+ next.Month - previous.Month // add difference in months+ (previous.Day <= next.Day ? 0 : -1); // if the day of the next date has not reached the day of the previous one, then the last month has not yet ended }
But if you still want to get the fractional parts of the months, you just need to add one more term to the return:
+ (next.Day - previous.Day) / DateTime.DaysInMonth(previous.Year, previous.Month)