How to calculate difference in hours (decimal) between two dates in SQL Server?

后端 未结 8 1897
情深已故
情深已故 2020-11-30 23:44

I have to calculate the difference in hours (decimal type) between two dates in SQL Server 2008.

I couldn\'t find any useful technique to convert datetime to decimal

相关标签:
8条回答
  • 2020-12-01 00:03

    SELECT DATEDIFF(hh, firstDate, secondDate) FROM tableName WHERE ...

    0 讨论(0)
  • 2020-12-01 00:07

    Just subtract the two datetime values and multiply by 24:

      Select Cast((@DateTime2 - @DateTime1) as Float) * 24.0
    

    a test script might 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 1 Jan 1900, and the second integer (representing the time) is the number of (1) ticks since Midnight. (For SmallDatetimes the time portion integer is the number of minutes since midnight). Any arithmetic done on the values uses the time portion as a fraction of a day. 6am = 0.25, noon = 0.5, etc... See MSDN link here for more details.

    So Cast((@Dt2 - @Dt1) as Float) gives you total days between two datetimes. Multiply by 24 to convert to hours. If you need total minutes, Multiple by Minutes per day (24 * 60 = 1440) instead of 24...

    NOTE 1: This is not the same as a dotNet or javaScript tick - this tick is about 3.33 milliseconds.

    0 讨论(0)
提交回复
热议问题