views:

84

answers:

3

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.

A: 

see also: DateDiff()
http://msdn.microsoft.com/en-us/library/b5xbyt6f%28VS.80%29.aspx

bugtussle
+1  A: 

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)
Darin Dimitrov
fivebob
A: 

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 from MS suggested)way. Here is an interesting blog: http://blogs.msdn.com/b/vbfaq/archive/2004/05/30/144571.aspx

Tim Schmelter