DATEDIFF in HH:MM:SS format

前端 未结 6 968
予麋鹿
予麋鹿 2020-12-06 10:29

I need to calculate the total length in terms of Hours, Minutes, Seconds, and the average length, given some data with start time and end time.

For example the resul

6条回答
  •  隐瞒了意图╮
    2020-12-06 11:05

    A way that avoids overflows and can include days and go all the way to milliseconds in the output:

    DECLARE @startDate AS DATETIME = '2018-06-01 14:20:02.100'
    DECLARE @endDate AS DATETIME = '2018-06-02 15:23:09.000'
    SELECT CAST(DATEDIFF(day,'1900-01-01', @endDate - @startDate) AS VARCHAR) +  'd ' + CONVERT(varchar(22), @endDate - @startDate, 114)
    

    The above will return

    1d 01:03:06:900

    And, off course, you can use the formatting of your choice

    SQL Supports datetime substraction which outputs a new datetime relative to the MIN date (for instance 1900-01-01, you can probably get this value from some system variable) This works better than DATEDIFF, because DATEDIFF will count ONE for each "datepart boundaries crossed", even if the elapsed time is less than a whole datapart. Another nice thing about this method is that it allows you to use the date formatting conversions.

提交回复
热议问题