我有以下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
我想要做的是找出两个日期之间有多少个月。任何帮助将不胜感激。
答案 0 :(得分:5)
以下是您可以使用的方法:
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)
答案 1 :(得分:0)
这也应该有效:
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