Calculate DateDiff in SQL in Days:Hours:Mins:Seconds format

user1423779 picture user1423779 · May 29, 2012 · Viewed 48k times · Source

I am currently working an SQL script to calculate the difference between two dates which would give me the result in DD:HH:MI:SEC format. Example: Date 1: 7/30/12 4:00 PM Date 2: 5/4/12 10:31 AM

And the result should be 87:05:29:00

Can you kindly help with the script for this? Regards, Arjun

Answer

Arion picture Arion · May 29, 2012

If you are using sql-server then you can do this:

declare @x int, 
        @dt1 smalldatetime = '1996-03-25 03:24:16', 
        @dt2 smalldatetime = getdate()

set @x = datediff (s, @dt1, @dt2)


SELECT convert(varchar, @x / (60 * 60 * 24)) + ':'
+ convert(varchar, dateadd(s, @x, convert(datetime2, '0001-01-01')), 108)

Reference here