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)
Share:
18,890
Icemanind
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, 2022

Comments

  • Icemanind
    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
      CodingGorilla almost 14 years
      I suppose it depends on your definition of months, do you mean calendar months or groups of 30 days?
    • bugtussle
      bugtussle almost 14 years
    • hollsk
      hollsk almost 14 years
      Why do you hate February? :-(
    • wirol
      wirol over 12 years
      Here is the simple and short code in case, you still couldn't get the answer, see this POST stackoverflow.com/questions/8820603/…
  • fivebob
    fivebob almost 14 years
    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.
  • Krisztián Balla
    Krisztián Balla almost 9 years
    Thanks, this also works for C#. @fivebob: Your way of seeing it, can't be answered, since months have different lengths, right?