ExtensionMethod.NET Home of 820 C#, Visual Basic, F# and Javascript extension methods

GetMonthDiff

Compute dateTime difference

Source

/// <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);

Author: Alex-LEWIS

Submitted on: 12 aug 2015

Language: C#

Type: DateTime

Views: 2601