Calculating Number of Months between 2 dates
18,890
Here's a method you could use:
Public Shared Function MonthDifference(ByVal first As DateTime, ByVal second As DateTime) As Integer
Return Math.Abs((first.Month - second.Month) + 12 * (first.Year - second.Year))
End Function
like this:
Dim Date1 As New DateTime(2010,5,6)
Dim Date2 As New DateTime(2009,10,12)
Dim NumOfMonths = MonthDifference(Date1, Date2)
![Icemanind](https://i.stack.imgur.com/VkdLW.jpg?s=256&g=1)
Author by
Icemanind
I am a .NET developer. I am proficient in C# and I use ASP.Net Core, Winforms and WPF. I also dabble in React and Xamarin.
Updated on August 23, 2022Comments
-
Icemanind almost 2 years
I have the following VB.NET Code:
Dim Date1 As New DateTime(2010,5,6) Dim Date2 As New DateTime(2009,10,12) Dim NumOfMonths = 0 ' This is where I am stumped
What I am trying to do is find out how many months are between the 2 dates. Any help would be appreciated.
-
CodingGorilla almost 14 yearsI suppose it depends on your definition of months, do you mean calendar months or groups of 30 days?
-
bugtussle almost 14 yearssee also:
DateDiff()
docs.microsoft.com/en-us/dotnet/api/… -
hollsk almost 14 yearsWhy do you hate February? :-(
-
wirol over 12 yearsHere is the simple and short code in case, you still couldn't get the answer, see this POST stackoverflow.com/questions/8820603/…
-
-
fivebob almost 14 yearsThis will return the difference in the month number, but is that really the number of months difference between the two dates? e.g. It will return 1 if the dates are 30th Jun & 1st July of the same year.
-
Krisztián Balla almost 9 yearsThanks, this also works for C#. @fivebob: Your way of seeing it, can't be answered, since months have different lengths, right?