DateDiff to output hours and minutes

后端 未结 12 2014
半阙折子戏
半阙折子戏 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:41

    I would make your final select as:

    SELECT    EmplID
            , EmplName
            , InTime
            , [TimeOut]
            , [DateVisited]
            , CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60) + ':' +
              RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
              as TotalHours
    from times
    Order By EmplID, DateVisited 
    

    Any solution trying to use DATEDIFF(hour,... is bound to be complicated (if it's correct) because DATEDIFF counts transitions - DATEDIFF(hour,...09:59',...10:01') will return 1 because of the transition of the hour from 9 to 10. So I'm just using DATEDIFF on minutes.

    The above can still be subtly wrong if seconds are involved (it can slightly overcount because its counting minute transitions) so if you need second or millisecond accuracy you need to adjust the DATEDIFF to use those units and then apply suitable division constants (as per the hours one above) to just return hours and minutes.

提交回复
热议问题