I'm searching a way to get the difference between two times in SQL Server.
I would like a format hh:mm:ss
Example : 23:00:00 - 18:09:00 = 04:51:00
I tried with datediff()
but it only returns hours, minutes or seconds
[EDIT] :
For example : 23:00:00 + 02:00:00 = 01:00:00, how to get 25:00:00?
You can convert to a time:
select dateadd(second, datediff(second, date1, date2), cast('0:00:00' as time))
You can then use format()
or convert()
to format the value as a string the way you want.
Example
Declare @T1 time = '23:00'
Declare @T2 time = '18:09'
Select cast(cast(@T1 as datetime) - cast(@T2 as datetime) as time)
Returns
04:51:00.0000000
Or you can use Format() if 2012+
Select format(cast(@T1 as datetime) - cast(@T2 as datetime),'HH:mm:ss')
Returns
04:51:00
Though Others have already answered correctly. I would like to add another version.
declare @StartTime datetime, @EndTime datetime
select @StartTime = '08:40:18',@EndTime='18:52:48'
select convert(varchar(5),DateDiff(s, @StartTime, @EndTime)/3600)+':'
+ convert(varchar(5),DateDiff(s, @StartTime, @EndTime)%3600/60)+':'
+ convert(varchar(5),(DateDiff(s, @StartTime, @EndTime)%60)) as [hh:mm:ss]
Output: 10:12:30
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.