DateDiff to output hours and minutes

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

    No need to jump through hoops. Subtracting Start from End essentially gives you the timespan (combining Vignesh Kumar's and Carl Nitzsche's answers) :

    SELECT *,
        --as a time object
        TotalHours = CONVERT(time, EndDate - StartDate),
        --as a formatted string
        TotalHoursText = CONVERT(varchar(20), EndDate - StartDate, 114)
    FROM (
        --some test values (across days, but OP only cares about the time, not date)
        SELECT
            StartDate = CONVERT(datetime,'20090213 02:44:37.923'),
            EndDate   = CONVERT(datetime,'20090715 13:24:45.837')
    ) t
    

    Ouput

    StartDate               EndDate                 TotalHours       TotalHoursText
    ----------------------- ----------------------- ---------------- --------------------
    2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 10:40:07.9130000 10:40:07:913
    

    See the full cast and convert options here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

提交回复
热议问题