Calculate Month difference between two Dates using C# and VB.net in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

Please guide 

CalculateMonth Difference between two date in VB.net in asp.net 

txtStartingDate.Text value is '01/11/2020'

txtEndingDate.Text value is '31/01/2021'

Month Difference between above two value is '3'

Dim d1a As DateTime = DateTime.Parse(txtStartingDate.Text, New System.Globalization.CultureInfo("pt-BR"))
Dim d2a As DateTime = DateTime.Parse(txtEndingDate.Text, New System.Globalization.CultureInfo("pt-BR"))
Dim M As Integer = Math.Abs((d1a.Year - d2a.Year))
Dim months As Integer = ((M * 12) + Math.Abs((d1a.Month - d2a.Month))) + 1

 

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi Mehram,

Use below code.

C#

string startDate = "01/11/2020";
string endDate = "31/01/2021";
DateTime d1a = DateTime.Parse(startDate, new System.Globalization.CultureInfo("pt-BR"));
DateTime d2a = DateTime.Parse(endDate, new System.Globalization.CultureInfo("pt-BR"));
int months = Math.Abs(d2a.Subtract(d1a).Days / (365 / 12));

VB.Net

Dim startDate As String = "01/11/2020"
Dim endDate As String = "31/01/2021"
Dim d1a As DateTime = DateTime.Parse(startDate, New System.Globalization.CultureInfo("pt-BR"))
Dim d2a As DateTime = DateTime.Parse(endDate, New System.Globalization.CultureInfo("pt-BR"))
Dim months As Integer = Math.Abs(d2a.Subtract(d1a).Days / (365 / 12))