Skip to content
Advertisement

Calculate time difference in days:hours:min:sec format

I have this query: Wherein I have to calculate the time difference in Days:Hours:min:sec format

Declare @t table (ID int, starttime datetime,EndTime Datetime)

Insert into @t values (1,'2019-11-16 09:39:04.000','2019-11-16 13:43:40.000')
Insert into @t values (1,'2019-11-16 16:49:42.000','2019-11-18 18:02:58.000')

select convert(varchar(550),DateDiff(day, starttime, EndTime)%3600)+'D : '+convert(varchar(5),DateDiff(s, starttime, EndTime)/3600%24)+'H : '+convert(varchar(5),DateDiff     (s,starttime, EndTime)%3600/60)+'M : '+convert(varchar(5),(DateDiff(s, starttime, EndTime)%60)) +'S'   as Duration 
from @t

Output:

Duration
0D : 4H : 4M : 36S  
2D : 1H : 13M : 16S  

My question is, how to calculate the sum of the 2 rows?

My desired output is:

Duration  
2D : 5H : 17M : 52S

Advertisement

Answer

Find the difference in second & do aggregation :

declare @seconds int

select @seconds = sum(datediff(second, starttime, EndTime))
from @t

select convert(varchar(255), (@seconds / 86400)) + 'D:' +
       convert(varchar(255), ((@seconds % 86400) /3600)) + 'H:'+
       convert(varchar(255), (((@seconds % 86400) % 3600) / 60)) + 'M:'+
       convert(varchar(255), (((@seconds % 86400) % 3600) % 60)) + 'S' as Duration  
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement