【问题标题】:Using DateDiff() in VB to find the difference between 2 dates in months and days在 VB 中使用 DateDiff() 来查找 2 个日期在月和日之间的差异
【发布时间】:2014-08-07 13:33:12
【问题描述】:

我需要在 VB 中找出 2 个日期的月份和天数之间的差异。使用DateDiff() 函数,我没有得到想要的结果,因为DateDiff() 只减去了相应的值。例如:

DateDiff("m", '31/01/2012', '1/02/2012')

返回 1 个月,这是不正确的。我如何做到这一点?

【问题讨论】:

  • 期望的结果是什么?你想要只计算天数的结果还是?
  • 1 天,在上述示例的情况下为 0 个月。我想要月份和日期形式的结果。例如:如果开始日期是 2012 年 1 月 31 日,结束日期是 2012 年 5 月 3 日,我需要 1 个月零 5 天作为答案。
  • 为此,您的“月”应包含多少天? 30、31、28、29?
  • 您将需要创建一个自定义函数来返回该类型的信息,方法是将天数 转换为月部分和日部分。您的自定义函数需要考虑每个月的天数(例如,2 月 1 日至 4 月 3 日为 63 天,结果为 2 个月 3 天——而 4 月 1 日至 6 月 4 日为 64 天,但也会为 2 个月 3 天)。您还需要考虑闰年...
  • @RitwikDey 是的,你可以,但会更困难(再次)。例如。 Month(d1) - Month(d2) 仅在 d1d2 属于同一年份时才有意义。 DateDiff 处理所有这些。另见this discussion

标签: vba datetime datediff


【解决方案1】:

我已经解决了这个问题。我必须编写一个函数来满足我的需要。算法是:

1) 使用 DateDiff 计算 2 天之间的月差。 2) 将两个日期的“dd”部分存储在 2 个不同的变量中。 3) 如果开始日期的'dd'大于结束日期的'dd',月份为Step1.value-1,否则月份为step1.value 4) 将开始日期增加我们从步骤 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)

【讨论】:

  • 那个for循环是not really necessary...
  • @GSerg : 你能为 for 循环写一个替代方案吗?
  • Day = DateDiff("d", temp, EndDate)
【解决方案2】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多