views:

412

answers:

3

Hi,

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.

A: 

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.

jball
I'm trying to calculate the how much time has spent. You see tsStart happened first at 12:27:30 (pm) , tsEnd happened later at 00:10:25(am) which is 12 hr different.
Angkor Wat
+1  A: 

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
Edward Robertson
This gives the wrong value, however. The correct value of r is 11:42:55, not 12:17:05.
Jeff Sternal
It is positive, but also wrong.
Hans Passant
*facepalm* How embarrasing...
Edward Robertson
+1  A: 

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.

Jeff Sternal
That assumes that tsEnd is never later by more than 1 day.
jball
True, but there's no way to tell otherwise, given the constraints presented here.
Jeff Sternal
This works well. Thanks a lot.
Angkor Wat