Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

datediff

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

like image 663
user1423779 Avatar asked May 29 '12 13:05

user1423779


People also ask

How do you calculate time difference between days hours and minutes in SQL Server?

To calculate the difference between the arrival and the departure in T-SQL, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument can be microsecond , second , minute , hour , day , week , month , quarter , or year .

How is datediff calculated in SQL?

You can use either Day of year ("y") or Day of month ("m") to measure the number of days between date1 and date2 ("d"). DateDiff returns the number of weeks between the two dates when the interval is Weekday ("w").

How do I get the difference between two dates and days in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.


1 Answers

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

like image 104
Arion Avatar answered Sep 30 '22 02:09

Arion