How to get the number of months between two dates in VB.NET

1 Answer

0 votes
Imports System

Module Program

    ''' <summary>
    ''' Returns the number of complete months between two dates.
    ''' </summary>
    ''' <param name="startdate">Start date.</param>
    ''' <param name="enddate">End date.</param>
    ''' <returns>Number of complete months.</returns>
    Function GetMonthsBetween(startdate As Date, enddate As Date) As Integer

        ' Calculate the raw month difference.
        Dim months As Integer =
            ((enddate.Year - startdate.Year) * 12) +
            (enddate.Month - startdate.Month)

        ' If the end day is before the start day,
        ' the last month has not been completed.
        If enddate.Day < startdate.Day Then
            months -= 1
        End If

        Return months

    End Function

    Sub Main()

        ' Start date: 2026/1/15
        Dim startdate As New Date(2026, 1, 15)

        ' End date: 2027/7/20
        Dim enddate As New Date(2027, 7, 20)

        Dim months As Integer = GetMonthsBetween(startdate, enddate)

        Console.WriteLine($"Months between dates: {months}")

    End Sub

End Module
 
 
' run:
'
' Months between dates: 18
'

 



answered 3 days ago by avibootz
...