Just subtract the two datetime values ββand multiply by 24:
Select Cast((@DateTime2 - @DateTime1) as Float) * 24.0
The test script could be:
Declare @Dt1 dateTime Set @Dt1 = '12 Jan 2009 11:34:12' Declare @Dt2 dateTime Set @Dt2 = getdate() Select Cast((@Dt2 - @Dt1) as Float) * 24.0
This works because all datetimes are stored internally as a pair of integers, the first integer is the number of days since January 1, 1900, and the second integer (representing time) is the number ( 1 ) of ticks from midnight. (For SmallDatetime, the integer time is the number of minutes since midnight). Any arithmetic performed by values ββuses the time part as part of the day. 6am = 0.25, noon = 0.5, etc. See the MSDN link here for more details.
So Cast ((@ Dt2 - @ Dt1) like Float) gives you the total number of days between two dates. Multiply by 24 to convert to hours. If you need full minutes, several minutes per day (24 * 60 = 1440) instead of 24 ...
NOTE 1 This is not the same as the dotNet or javaScript tick - this tick is about 3.33 milliseconds.
Charles Bretana Nov 20 '09 at 14:19 2009-11-20 14:19
source share