则DateDiff计算不正确:准确日期差异
DateDiff("m", "30/06/2011", "24/06/2012") will return 12
,但我需要返回11,因为真正的区别是11个月和25天
也许任何人有这个问题
具体的解决方案这将是非常适合我:11 个月和25 天
则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
纯粹的DateDiff
不会得到它。如果您使用此custom made function,你得到的结果你想要的方式,如:
0 years, 1 months, 1 days
您也可以看看有(中端单六)DateDif
功能。请注意,DateDif()在结束月份的天数少于开始月份时仍会给出一些可能意外的结果(即负数天数)。