How can I use the datediff to calcualte the time difference between a time that starts before midnight and a time that ends after midnight?
The following function will handle this:
Public Function TimeDuration(dtmFrom As Date, dtmTo As Date, _
Optional blnShowdays As Boolean = False) As String
' Returns duration between two date/time values
' in format hh:nn:ss, or d:hh:nn:ss if optional
' blnShowDays argument is True.
' If 'time values' only passed into function and
' 'from' time is later than or equal to 'to' time, assumed that
' this relates to a 'shift' spanning midnight and one day
' is therefore subtracted from 'from' time
Dim dtmTime As Date
Dim lngDays As Long
Dim strDays As String
Dim strHours As String
' subtract one day from 'from' time if later than or same as 'to' time
If dtmTo <= dtmFrom Then
If Int(dtmFrom) + Int(dtmTo) = 0 Then
dtmFrom = dtmFrom - 1
End If
End If
' get duration as date time data type
dtmTime = dtmTo - dtmFrom
' get whole days
lngDays = Int(dtmTime)
strDays = CStr(lngDays)
' get hours
strHours = Format(dtmTime, "hh")
If blnShowdays Then
TimeDuration = lngDays & ":" & strHours & Format(dtmTime, ":nn:ss")
Else
TimeDuration = Format((Val(strDays) * 24) + Val(strHours), "00") & _
Format(dtmTime, ":nn:ss")
End If
End Function
Note that it returns a string, in the format hh:nn:ss by default, so you cannot do date/time arithmetic on the returned value. You can see how it works in the debug window:
? TimeDuration(#22:00#,#02:04#)
04:04:00
whereas:
? TimeDuration(#20:00#,#22:04#)
02:04:00
Both are correct in the context of the former's times being on subsequent days. The function will of course also work if full date/time values are passed into it, in which case the values can be more than one day apart if necessary.