tags:

views:

36

answers:

3

I'm using Computed Columns to provide me with the following information:

Hours, Minutes, and Seconds between a Start DateTime and Finish DateTime (Where Minutes and Seconds are between 0 and 59 and Hours can be any value 0 or greater)

Computed Column for Seconds:

datediff(second,[Start],[Finish]) % 60

Computed Column for Minutes:

floor(datediff(second,[Start],[Finish]) / 60.0) % 60

Computed Column for Hours:

floor(datediff(second,[Start],[Finish]) / 3600.0)

Here's the table for reference

alt text

Note: I'm also calculating TotalElapsedSeconds, TotalElapsedMinutes, and TotalElapsedHours in other computed columns, but those are easy. I just feel like I might be missing out on a nice built in function in SQL.

Note: I have a check constraint that ensures that Finish > Start

+1  A: 

if you are using sql server, you can use

datediff(minute,[Start],[Finish])
datediff(hour,[Start],[Finish])
sza
This gives incorrect values for the following situation: SELECT DATEDIFF(hour,'1994-01-01 11:59:59','1994-01-01 12:00:00')
hamlin11
What did you get?
sza
+1  A: 

In terms of finding the hours, minutes, and seconds between two dates similar to the functions you are using, you could use DatePart like so:

DatePart(hh, Finish - Start)
DatePart(mi, Finish - Start)
DatePart(s, Finish - Start)
Thomas
hamlin11
@hamlin11 - Your calculation of hours is the total hours difference between the two datetimes but that is very different than the hours portion (or minutes or seconds) of the difference which is what I presumed you were trying to get to. If you want the difference in hours between two dates you should simply use `DateDiff(hh, Date1, Date2).` I would think you would want the three values to represent the same thing (i.e. total hours, total min, total seconds or the diff's hour portion, min portion, sec portion).
Thomas
@Thomas, I understand where you were coming from. I was just making a distinction between your answer (what most people will come here looking for) and what my specific question was asking for. Good answer, thanks
hamlin11
+1  A: 

Does your dialect of SQL support this syntax for date interval math:

db=> select to_char(timestamp '2010-05-21 10:10:10' - '2009-10-11', 'ddd hh24:mi:ss');
   to_char    
--------------
 222 10:10:10
(1 row)

db=> select to_char(timestamp '2010-05-21 10:10:10' - '2001-10-11', 'ddd hh24:mi:ss');
    to_char    
---------------
 3144 10:10:10
(1 row)

db=> select to_char(timestamp '2010-05-21 10:10:10' - '2010-05-21', 'ddd hh24:mi:ss');
   to_char    
--------------
 000 10:10:10
(1 row)
stac