4

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.

Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • 2
    I suppose it depends on your definition of months, do you mean calendar months or groups of 30 days? – CodingGorilla Jul 14 '10 at 20:04
  • Why do you hate February? :-( – hollsk Jul 14 '10 at 20:06
  • Here is the simple and short code in case, you still couldn't get the answer, see this [POST](http://stackoverflow.com/questions/8820603/how-a-month-is-defined-in-the-rest-of-the-world) http://stackoverflow.com/questions/8820603/how-a-month-is-defined-in-the-rest-of-the-world – wirol Jan 11 '12 at 15:53
  • see also: `DateDiff()` https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.dateandtime.datediff – bugtussle Jul 14 '10 at 20:04

1 Answers1

6

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This 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. – fivebob Jul 14 '10 at 21:21
  • Thanks, this also works for C#. @fivebob: Your way of seeing it, can't be answered, since months have different lengths, right? – Krisztián Balla Aug 17 '15 at 09:13