DateDiff 计算不正确:
DateDiff("m", "30/06/2011", "24/06/2012") will return 12
但我需要返回 11,因为真正的差异是 11 个月和 25 天
也许有人对这个问题有具体的解决方案
这对我来说是理想的:11个月零25天
这是比上述定制功能更清洁的解决方案。大多数情况下,它使用内置的 DateDiff 函数,但如果它向上取整,则会调整答案。即使第一个日期晚于第二个日期,我的函数也会给您带来差异,并且可以选择添加一些文字说明。
Function YearsMonthsDays(Date1 As Date, _
Date2 As Date, _
Optional ShowAll As Boolean = False, _
Optional Grammar As Boolean = True, _
Optional MinusText As String = "Minus " _
) As String
Dim dTempDate As Date
Dim iYears As Integer
Dim iMonths As Integer
Dim iDays As Integer
Dim sYears As String
Dim sMonths As String
Dim sDays As String
Dim sGrammar(-1 To 0) As String
Dim sMinusText As String
If Grammar = True Then
sGrammar(0) = "s"
End If
If Date1 > Date2 Then
dTempDate = Date1
Date1 = Date2
Date2 = dTempDate
sMinusText = MinusText
End If
iYears = DateDiff("yyyy", Date1, Date2)
Date1 = DateAdd("yyyy", iYears, Date1)
If Date1 > Date2 Then
iYears = iYears - 1
Date1 = DateAdd("yyyy", -1, Date1)
End If
iMonths = DateDiff("M", Date1, Date2)
Date1 = DateAdd("M", iMonths, Date1)
If Date1 > Date2 Then
iMonths = iMonths - 1
Date1 = DateAdd("m", -1, Date1)
End If
iDays = DateDiff("d", Date1, Date2)
If ShowAll Or iYears > 0 Then
sYears = iYears & " year" & sGrammar((iYears = 1)) & ", "
End If
If ShowAll Or iYears > 0 Or iMonths > 0 Then
sMonths = iMonths & " month" & sGrammar((iMonths = 1)) & ", "
End If
sDays = iDays & " day" & sGrammar((iDays = 1))
YearsMonthsDays = sMinusText & sYears & sMonths & sDays
End Function