Question

These two TimeSpan are stored in the Database with 24hr format. No date, only TimeSpan.

Dim r As TimeSpan
Dim tsStart As TimeSpan
Dim tsEnd As TimeSpan

'tsStard is 12:27:30 (pm) this happened first
'tsEnd is 00:10:25 (am) then this happened later

'You can't store 24:10:25 in the column type Time(7)

r = tsEnd.Subtract(tsStart)

'the r = -12:17:05

Is there any TimeSpan method to get this right? Thank you.

Was it helpful?

Solution

If you know that tsEnd always represents a later point in time than tsStart but your database doesn't store the dates, you can solve this by adding 24 hours to the end when the end is less than the start (pardon the C# syntax):

if (tsEnd < tsStart) {
    r = tsEnd.Add(new TimeSpan(24, 0, 0)).Subtract(tsStart);
} else {
    r = tsEnd.Subtract(tsStart);
}

As jball noted in the comments, this assumes that tsEnd is never later by more than one day, though we have no way to determine otherwise.

OTHER TIPS

If you use the Duration() method on TimeSpan, it will guarantee that your result is positive, no matter what order you do the subtraction in.

For example:

Dim r As TimeSpan
Dim tsStart As TimeSpan
Dim tsEnd As TimeSpan

'tsStart is 12:27:30 
'tsEnd is 00:10:25 

r = tsEnd.Subtract(tsStart).Duration()
'r = 12:17:05

tsEnd is less than tsStart, so r = tsEnd.Subtract(tsStart) should result in a negative number. Perhaps you want to subtract tsEnd from tsStart r = tsStart.Subtract(tsEnd), or your variables are being set to the reverse of what they should be?

Depending on your situation you may want to call r = r.Duration(), which returns the absolute value of r.

If you are worried about wrapping days, you'll need the date - there's no way to know how many days have gone by just from the time component.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top