I am using the below code to show the date difference in Day:Hour:Minute format.
Function TimeSpan(dt1, dt2)
Dim seconds,minutes,hours,days
If (isDate(dt1) And IsDate(dt2)) = false Then
TimeSpan = "00:00:00"
Exit Function
End If
seconds = Abs(DateDiff("S", dt1, dt2))
minutes = seconds \ 60
hours = minutes \ 60
days = hours \ 24
minutes = minutes mod 60
seconds = seconds mod 60
days = days mod 24
if len(hours) = 1 then hours = "0" & hours
TimeSpan = days& ":" & _
RIGHT("00" & hours , 2) & ":" & _
RIGHT("00" & minutes, 2)
End Function
But it is not producing expected values for some cases.
D1=#9/24/2012 8:09:15 AM# and D2=#9/25/2012 8:09:15 AM# gives correct data like 1:24:00 whereas below are producing error when working with VBScript and Excel.
D1=#9/5/2012 8:45:43 AM# and D2=#9/25/2012 8:45:43 AM# result=0.888888888888889
D1=#9/6/2012 8:29:34 AM# and D2=#9/17/2012 8:59:36 AM# result=0.503125
Can you explain why so?
Thanks
Try my answer from an earlier post in your UDF as the following: This answer is in VBA
Please declare all variables and force yourself to declare by adding option explicit 🙂
UDF Output:
But I really suggest you to use Excel sheet functions if you have the freedom and possibility to do so.
If date difference is more than 31 days
Then use the solution as per this article
Incorporate the
DateDiffto the UDF.