Calculating the number of months between two dates

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'm trying to do is figure out how many months between two dates. Any help would be appreciated.

+4
source share
3 answers

Here you can use the method

 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) 
+4
source

This should also work:

 Dim Date1 As New DateTime(2010, 5, 6) Dim Date2 As New DateTime(2009, 10, 12) Dim timeDifference As TimeSpan = Date1 - Date2 Dim resultDate As DateTime = DateTime.MinValue + timeDifference Dim monthDifference As Int32 = resultDate.Month - 1 

But I think the DateDiff version is the easiest (and with MS suggested) way. Here is an interesting blog: http://blogs.msdn.com/b/vbfaq/archive/2004/05/30/144571.aspx

0
source

Source: https://habr.com/ru/post/1315711/


All Articles