ralphtrent
Programmer
Does anyone know of a way to do a datediff like function for times with milliseconds?
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
a = timer
'do stuff
'do more stuff
objShell.Popup "Stuff took " & timer - a " seconds!"
Option Explicit
Dim strTime1, strTime2, strMilliDiff
strTime1 = "12:50:15.096"
strTime2 = "12:50:15.200"
strMilliDiff = GetMilliDiff(strTime1, strTime2)
TestMilliDiff strMilliDiff, "104"
strTime1 = "12:50:15.096"
strTime2 = "12:50:16.296"
strMilliDiff = GetMilliDiff(strTime1, strTime2)
TestMilliDiff strMilliDiff, "1200"
strTime1 = "12:50:16.296"
strTime2 = "12:50:15.096"
strMilliDiff = GetMilliDiff(strTime1, strTime2)
TestMilliDiff strMilliDiff, "1200"
strTime1 = "12:50:15.096"
strTime2 = "12:50:16.006"
strMilliDiff = GetMilliDiff(strTime1, strTime2)
TestMilliDiff strMilliDiff, "910"
Sub TestMilliDiff (strToTest, strShouldBe)
If strToTest = strShouldBe Then
WScript.Echo "Test passed " & strToTest & " = " & strShouldBe
Else
WScript.Echo "Test FAILED " & strToTest & " <> " & strShouldBe
End If
End Sub
Function GetMilliDiff(strT1, strT2)
Dim time1, time2, milli1, milli2, arr1, arr2, timediff, millidiff
arr1 = Split(strT1, ".")
arr2 = Split(strT2, ".")
If UBound(arr1) > 1 Or UBound(arr2) > 1 Then
'Invalid time submitted
GetMilliDiff = Null
Exit Function
End If
If UBound(arr1) = 1 Then
time1 = arr1(0)
milli1 = arr1(1)
Else
Time1 = arr1(0)
milli1 = "0"
End If
If UBound(arr2) = 1 Then
time2 = arr2(0)
milli2 = arr2(1)
Else
time2 = arr2(0)
milli2 = "0"
End If
If CDate(time2) < CDate(time1) Then
'Submitted in wrong order
GetMilliDiff = Null
Exit Function
End If
'First, get the second difference from the times and convert to milli
timediff = DateDiff("s", time1, time2) * 1000
'Now there will be two possibilities for the milli diff
If milli1 <= milli2 Then
millidiff = CInt(milli2) - CInt(milli1)
Else
'Get diff from milli1 to 1000 then 1000 to milli2 and subtract 1000 to make up
'for the 1 second this process adds.
millidiff = (1000 - CInt(milli1)) + CInt(milli2) - 1000
End If
GetMilliDiff = CStr(timediff + millidiff)
End Function