GetTotalMonthDiff
Compute dateTime difference precisely
Source
/// <summary>
/// Compute dateTime difference precisely
/// Alex-LEWIS, 2015-08-11
/// </summary>
/// <param name="dt1"></param>
/// <param name="dt2"></param>
/// <returns></returns>
public static double GetTotalMonthDiff(this DateTime dt1, DateTime dt2)
{
var l = dt1 < dt2 ? dt1 : dt2;
var r = dt1 >= dt2 ? dt1 : dt2;
var lDfM = DateTime.DaysInMonth(l.Year, l.Month);
var rDfM = DateTime.DaysInMonth(r.Year, r.Month);
var dayFixOne = l.Day == r.Day
? 0d
: l.Day > r.Day
? r.Day * 1d / rDfM - l.Day * 1d / lDfM
: (r.Day - l.Day) * 1d / rDfM;
return dayFixOne
+ (l.Month == r.Month ? 0 : r.Month - l.Month)
+ (l.Year == r.Year ? 0 : (r.Year - l.Year) * 12);
}
Example
DateTime dt1 = new DateTime(2015, 08, 11);
DateTime dt2 = new DateTime(1992, 10, 10);
var monthTotalDiff = dt1.GetMonthDiff(dt2);