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

后端 未结 8 1896
情深已故
情深已故 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-11-30 23:51

    DATEDIFF but note it returns an integer so if you need fractions of hours use something like this:-

    CAST(DATEDIFF(ss, startDate, endDate) AS decimal(precision, scale)) / 3600
    
    0 讨论(0)
  • 2020-11-30 23:52
    Declare @date1 datetime
    Declare @date2 datetime
    
    Set @date1 = '11/20/2009 11:00:00 AM'
    Set @date2 = '11/20/2009 12:00:00 PM'
    
    Select Cast(DateDiff(hh, @date1, @date2) as decimal(3,2)) as HoursApart
    

    Result = 1.00

    0 讨论(0)
  • 2020-11-30 23:55

    DATEDIFF(hour, start_date, end_date) will give you the number of hour boundaries crossed between start_date and end_date.

    If you need the number of fractional hours, you can use DATEDIFF at a higher resolution and divide the result:

    DATEDIFF(second, start_date, end_date) / 3600.0
    

    The documentation for DATEDIFF is available on MSDN:

    http://msdn.microsoft.com/en-us/library/ms189794%28SQL.105%29.aspx

    0 讨论(0)
  • 2020-11-30 23:56

    You are probably looking for the DATEDIFF function.

    DATEDIFF ( datepart , startdate , enddate )

    Where you code might look like this:

    DATEDIFF ( hh , startdate , enddate )

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

    Using Postgres I had issues with DATEDIFF, but had success with this:

      DATE_PART('day',(delivery_time)::timestamp - (placed_time)::timestamp) * 24 + 
      DATE_PART('hour',(delivery_time)::timestamp - (placed_time)::timestamp) +
      DATE_PART('minute',(delivery_time)::timestamp - (placed_time)::timestamp) / 60
    

    which gave me an output like "14.3"

    0 讨论(0)
  • 2020-12-01 00:00
    DATEDIFF(minute,startdate,enddate)/60.0)
    

    Or use this for 2 decimal places:

    CAST(DATEDIFF(minute,startdate,enddate)/60.0 as decimal(18,2))
    
    0 讨论(0)
提交回复
热议问题