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