GetMonthDiff

/// <summary>
/// Compute dateTime difference
/// Alex-LEWIS, 2015-08-11
/// </summary>
/// <param name="dt1"></param>
/// <param name="dt2"></param>
/// <returns></returns>
public static int GetMonthDiff(this DateTime dt1, DateTime dt2)
{
  var l = dt1 < dt2 ? dt1 : dt2;
  var r = dt1 >= dt2 ? dt1 : dt2;
  return (l.Day == r.Day ? 0 : l.Day > r.Day ? 0 : 1)
    + (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 monthDiff = dt1.GetMonthDiff(dt2);

Description

Compute dateTime difference

Details

Double click on the code to select all.

 

;