VBA中两个日期之间的间隔

时间:2019-01-07 14:44:33

标签: excel vba

开始时间fullTextEntityManager.createIndexer().startAndWait() ,结束时间"08:58"。预期结果为8.39,表示经过8小时39分钟的时间。我尝试过:

"17:37"

但是它会在数小时内计算出错误的结果。出奇! 您会分享一些建议来计算预期结果吗?

6 个答案:

答案 0 :(得分:1)

尝试一下:

Sub Test()
    Dim minutes As Long
    Dim d1 As Date, d2 As Date
    d1 = "2018-01-01 08:58:00"
    d2 = "2018-01-01 17:37:00"
    minutes = DateDiff("n", d1, d2)
    ' Will print 8.39
    MsgBox Int(minutes / 60) & "." & minutes Mod 60
End Sub

答案 1 :(得分:1)

Function UDF_datediff(d1 As Date, d2 As Date) As Double
    Dim difference AS Double
    difference = d2 - d1
    UDF_datediff = Sgn(difference) * CDbl(Format(difference , "hh.mm"))
End Function

在您的示例中,d2-d1是1899-12-30 08:37:00的DateTime-将其格式设置为小时(2位数字),小数点,分钟(2位数字),然后转换为双精度并纠正符号。

答案 2 :(得分:0)

尝试

Sub test()
    Dim d1 As Date, d2 As Date
    Dim m As Double

    d1 = TimeValue("08:58")
    d2 = TimeValue("17:37")
    m = UDF_datediff(d1, d2)
    MsgBox m
    MsgBox Format(m / 24, "hh:mm")
End Sub

UDF

Function UDF_datediff(d1 As Date, d2 As Date) As Double

    UDF_datediff = (d2 - d1) * 24
End Function

答案 3 :(得分:0)

实际上并不需要

const。您可以使用一个简单的“减号”来查看发生了什么:

class

VBA中的日期显示为双精度数字。因此,如果您编写0.373611111111111并将其格式化为VBA中的“日期”,则会得到:

DateDiff

通过在立即窗口 Ctrl + G 中写入以下内容,可以获得上述双精度值:

Sub TestMe() 

    With Worksheets(1)
        Dim d1 As Date: d1 = 0.373611111111111 '08:58:00
        Dim d2 As Date: d2 = 0.734027777777778 '17:37:00
    End With
    Debug.Print UdfDatediff(d1, d2)            '08:39:00

End Sub

Function UdfDatediff(d1 As Date, d2 As Date) As Date

    UdfDatediff = Abs(d1 - d2)

End Function

在Excel中,日期也显示为双精度数字,但对于 1900 年的前两个月,该日期与VBA中的日期略有不同(请参见{{ 3}})。

答案 4 :(得分:-1)

或者-假设时间以一天的小数形式存储

 Function UDF_datediff(d1 As Date, d2 As Date) As Double
    d2 = d2-int(d2) 'remove date portion
    d1= d1 - int(d1)
    UDF_datediff = (d2-d1)*24
  End Function

答案 5 :(得分:-1)

一般的答案是这样的:

      Format(CDate(d2-d1),"h:m")

特别是对于您的开始和结束时间,此表达式将产生“ 8:39”结果。

如果您需要从中提取小时和分钟,可以执行以下操作:

Dim sDuration as String
Dim iCol as Long
Dim sH as String
Dim sM as String
Dim iH as Long
Dim iM as Long

sDuration = Format(CDate(d2-d1),"h:m") ' the "8:39" in your case
iCol =InStr(sDuration, ":") 
sH = Left(sDuration, iCol - 1)
sM = Mid(sDuration, iCol + 1, 2) ' length of 2 or any longer
iH = CInt(sH)
iM = CInt(sM)

您始终可以使用“数字”,将小数转换为24乘以60,四舍五入...如

iH = Int(CDate(d2-d1)*24) ' to get the hours

等(“分钟”要复杂一点)