![](/img/trans.png)
[英]Using VBA unable to get the difference between two dates in months and remaining days
[英]Using DateDiff() in VB to find the difference between 2 dates in months and days
我需要在 VB 中找到以月和天为单位的 2 个日期之间的差异。 使用DateDiff()
函数,我没有得到想要的结果,因为DateDiff()
只减去了相应的值。 例如:
DateDiff("m", '31/01/2012', '1/02/2012')
返回 1 个月,这是不正确的。 我如何实现这一目标?
我已经解决了。 我必须编写一个满足我需要的功能。 该算法是:
1)使用DateDiff计算2天之间的月份差异。 2)将两个日期的“ dd”部分存储在2个不同的变量中。 3)如果开始日期的'dd'大于结束日期的'dd',则month将为Step1.value-1,否则,month将为step1.value 4)将开始日期增加我们从中获得的months的值步骤3 5)运行从1到31的循环,将开始日期加1,直到等于结束日期。 6)天数将是(迭代次数)
代码是:
Dim temp As Date
Dim temp1 As Integer
Dim i As Integer
Dim day1 As Integer
Dim day2 As Integer
temp1 = DateDiff("m", StartDate, EndDate)
day1 = DatePart("d", StartDate)
day2 = DatePart("d", EndDate)
If day1 > day2 Then
temp = DateAdd("m", (temp1 - 1), StartDate)
Month = (temp1 - 1)
Else
temp = DateAdd("m", (temp1), StartDate)
Month = (temp1)
End If
For i = 1 To 31
If temp = EndDate Then Exit For
temp = DateAdd("d", 1, temp)
Next i
Day = (i - 1)
在 VB6.0 中计算两个日期之间的天数
Dim date1 As Date
Dim date2 As Date
date1 = CDate(Text1.Text)
date2 = CDate(Text2.Text)
Text3.Text = "Days between dates is: " & Format$(date2 - date1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.