Get Date difference in terms of Months using C# and VB.Net in ASP.Net

Last Reply on May 23, 2017 05:36 AM By dharmendr

Posted on May 23, 2017 05:33 AM

Sir,

  I have two dates as d1 & d2.

 d1 = 31 Dec 2016

 d2 = current date

To find difference in month I have used below method: 

totalvalidityLabel.Text = Convert.ToString(((d2 - d1).TotalDays) / 12);

 

But I getting wrong answer as 11.333333333333...

Is there DateDiff method available in c# as in vb. If yes then how to use it. If No, then how to get accurate difference in terms of months?

 

Posted on May 23, 2017 05:36 AM

Hi Sumeet,

Refer the below sample code.

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dim d1 As DateTime = Convert.ToDateTime("31 Dec 2015")
    Dim d2 As DateTime = DateTime.Now
    totalvalidityLabel.Text = MonthDifference(d1, d2).ToString()  ' -17 
    totalvalidityLabel.Text = MonthDifference(d2, d1).ToString()  ' 17
    totalvalidityLabel.Text = MonthDifference1(d1, d2).ToString() ' 17
    totalvalidityLabel.Text = MonthDifference1(d2, d1).ToString() ' 17
End Sub

' This returns a relative difference, meaning that if rValue is greater than lValue, then the return value will be negative.
Public Shared Function MonthDifference(lValue As DateTime, rValue As DateTime) As Integer
    Return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year)
End Function

'absolute difference.
Public Shared Function MonthDifference1(lValue As DateTime, rValue As DateTime) As Integer
    Return Math.Abs((lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year))
End Function

C#

protected void Page_Load(object sender, EventArgs e)
{
    DateTime d1 = Convert.ToDateTime("31 Dec 2015");
    DateTime d2 = DateTime.Now;
    totalvalidityLabel.Text = MonthDifference(d1, d2).ToString();  // -17 
    totalvalidityLabel.Text = MonthDifference(d2, d1).ToString();  // 17
    totalvalidityLabel.Text = MonthDifference1(d1, d2).ToString(); // 17
    totalvalidityLabel.Text = MonthDifference1(d2, d1).ToString(); // 17
}

// This returns a relative difference, meaning that if rValue is greater than lValue, then the return value will be negative.
public static int MonthDifference(DateTime lValue, DateTime rValue)
{
    return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);
}

//absolute difference.
public static int MonthDifference1(DateTime lValue, DateTime rValue)
{
    return Math.Abs((lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year));
}