DateDiff to output hours and minutes

后端 未结 12 1972
半阙折子戏
半阙折子戏 2020-12-09 09:47

my code gives TOTAL HOURS in hours, but i am trying to output something like

TotalHours 
  8:36

where 8 represents hour part and 36 repres

12条回答
  •  温柔的废话
    2020-12-09 10:36

    Since any DateTime can be cast to a float, and the decimal part of the number represent the time itself:

    DECLARE @date DATETIME = GETDATE()
    
    SELECT CAST(CAST(@date AS FLOAT) - FLOOR(CAST(@date AS FLOAT)) AS DATETIME
    

    This will result a datetime like '1900-01-01 hour of the day' you can cast it as time, timestamp or even use convert to get the formatted time.

    I guess this works in any version of SQL since cast a datetime to float is compatible since version 2005.

    Hope it helps.

提交回复
热议问题