Excel VBAfunction:从两个date计算秒(也计算毫秒)

这是这个问题和这个问题的后续工作

我创build了下面的VBA函数来计算两个date时间的秒数(也是毫秒数)。

function

Public Function ConvertDate(D1 As String, D2 As String) As Date Dim StrD1 As Date Dim StrD2 As Date StrD1 = CDate(Left(D1, 10) & " " & Replace(Mid(D1, 12, 8), ".", ":")) StrD2 = CDate(Left(D2, 10) & " " & Replace(Mid(D2, 12, 8), ".", ":")) ConvertDate = DateDiff("s", StrD2, StrD1) End Function 

情况1

给定date:

  2011-05-13-04.36.14.366004 2011-05-13-04.36.14.366005 

取得成果

 0 

预期成果

 0.000001 

情景2

给定date:

  2011-05-13-04.36.14.366004 2011-05-13-04.36.15.366005 

取得成果

 1 

预期成果

 1.000001 

情景3

给定date:

  2011-05-13-04.36.14.366004 2011-05-13-04.37.14.366005 

取得成果

 60 

预期成果

 60.000001 

一天是一天 date为1899年12月31日以后的每一天。 今天恰好是42556。 时间是一天中的小数部分。 今天中午是42556.5,今天下午06:00是42556.75。

一天24小时,一小时60分钟,一分钟60秒。 这意味着一天有86,400秒(24×60×60),一秒钟是一天的1/186秒(0.0000115740740740741)。 由于基数为24和基数为60的编号系统,Excel的15位浮点计算有时会计算(丢失less量)时间。

 Dim tm1 As String, tm2 As String Dim dbl1 As Double, dbl2 As Double Dim i As Long With Worksheets("Sheet9") For i = 1 To .Cells(.Rows.Count, "A").End(xlUp).Row Step 2 tm1 = .Cells(i, "A").Text tm2 = .Cells(i + 1, "A").Text dbl1 = CLng(CDate(Left(tm1, 10))) + _ TimeValue(Replace(Mid(tm1, 12, 8), Chr(46), Chr(58))) + _ (CDbl(Mid(tm1, 20)) / 86400) dbl2 = CLng(CDate(Left(tm2, 10))) + _ TimeValue(Replace(Mid(tm2, 12, 8), Chr(46), Chr(58))) + _ (CDbl(Mid(tm2, 20)) / 86400) .Cells(i + 1, "B") = (dbl2 - dbl1) * 86400 .Cells(i + 1, "B").NumberFormat = "0.000000" Next i End With 

上面的内容将你的时间和date作为文本,并计算一个伪十字的DateDiff到百万分之一秒的准确度。 结果以秒为单位显示,小数点以秒为单位。

millionth_seconds