Расчет количества месяцев между 2 датами - PullRequest
4 голосов
/ 15 июля 2010

У меня есть следующий код VB.NET:

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

Я пытаюсь выяснить, сколько месяцев проходит между двумя датами.Любая помощь будет оценена.

Ответы [ 2 ]

5 голосов
/ 15 июля 2010

Вот метод, который вы могли бы использовать:

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

вот так:

Dim Date1 As New DateTime(2010,5,6)
Dim Date2 As New DateTime(2009,10,12)
Dim NumOfMonths = MonthDifference(Date1, Date2)
0 голосов
/ 15 июля 2010

Это также должно работать:

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

Но я думаю, что версия DateDiff является самым простым (и предложенным MS) способом.Вот интересный блог: http://blogs.msdn.com/b/vbfaq/archive/2004/05/30/144571.aspx

...