To get the number of complete months you can do different things depending on your interpretation,
Public Function CompleteMonthsBetweenA( _ ByVal start As DateTime, _ ByVal end As DateTime) As Integer Dim invertor = 1 If (start > end) Then Dim tmp = end end = start start = tmp invertor = -1 End If Dim diff = ((end.Year - start.Year) * 12) + end.Month - start.Month If start.Day > end.Day Then Return (diff - 1) * invertor Else Return diff * invertor End If End Function
With this function the number of complete months between 31/05/2011 (dd/mm/yy) and 30/06/2011 is 0 but between 30/06/2011 and 31/07/2011 is 1. Which may or may not be what you expect.
Public Function CompleteMonthsBetweenB( _ ByVal start As DateTime, _ ByVal end As DateTime) As Integer Dim invertor = 1 If (start > end) Then Dim tmp = end end = start start = tmp invertor = -1 End If Dim diff = ((end.Year - start.Year) * 12) + end.Month - start.Month Dim startDaysInMonth = DateTime.DaysInMonth(start.Year, start.Month) Dim endDaysInMonth = DateTime.DaysInMonth(end.Year, end.Month) If (start.Day / startDaysInMonth) > (end.Day / endDaysInMonth) Then Return (diff - 1) * invertor Else Return diff * invertor End If End Function
With this function the ratio Day / DaysInMonth is taken so the relative completion of the two months can be assessed.
Public Function CompleteMonthsBetweenC( _ ByVal start As DateTime, _ ByVal enddate As DateTime) As Integer Dim invertor = 1 If (start > enddate) Then Dim tmp = enddate enddate = start start = tmp invertor = -1 End If Dim diff = ((enddate.Year - start.Year) * 12) + enddate.Month - start.Month Dim remainingDays = _ (DateTime.DaysInMonth(start.Year, start.Month) - start.Day) + enddate.Day If remainingDays < 15 Then Return (diff - 1) * invertor Else Return diff * invertor End If End Function
This function only rounds down if the surplus days are less than the magic number 15, which I think is what you are asking for in your update.
Public Function CompleteMonthsBetweenD( _ ByVal start As DateTime, _ ByVal end As DateTime) As Integer Return end.Subtract(start).TotalDays \ 30.436875 End Function
This function takes the simpler approach of dividing the total number of days by the average number of days per month in the Gregorian Calendar.