Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date difference formatted in Days Hours Minutes Seconds

Tags:

sql-server

Is there a way to get the time remaining(difference) between two dates?

For example I'd like to have it return 6 days, 10 hours, 3 minutes and 37 seconds.

like image 713
Wesley Avatar asked May 13 '14 11:05

Wesley


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 do I calculate hours between two dates in SQL?

SQL Server DATEDIFF() Function The DATEDIFF() function returns the difference between two dates.

How can calculate time difference between minutes and seconds in SQL Server?

To calculate the difference between the timestamps in MySQL, use the TIMESTAMPDIFF(unit, start, end) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR . To get the difference in seconds as we have done here, choose SECOND .


1 Answers

The following select should work:

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)

Another option that is closer to your desired output is:

DECLARE @start DATETIME ,
    @end DATETIME,
    @x INT

SELECT  @start = '2009-01-01' ,
        @end = DATEADD(ss, 5, DATEADD(mi, 52, DATEADD(hh, 18, DATEADD(dd, 2, @start)))),
        @x = DATEDIFF(s, @start, @end)

SELECT  CONVERT(VARCHAR, DATEDIFF(dd, @start, @end)) + ' Days '
        + CONVERT(VARCHAR, DATEDIFF(hh, @start, @end) % 24) + ' Hours '
        + CONVERT(VARCHAR, DATEDIFF(mi, @start, @end) % 60) + ' Minutes '
        + CONVERT(VARCHAR, DATEPART(ss, DATEADD(s, @x, CONVERT(DATETIME2, '0001-01-01')))) + ' Seconds'

UPDATED ANSWER (04/12/2018): Accounts for difference in lower order date part that affects the higher order date part (i.e. 23 hour difference will now result in 0 days 23 hours)!

DECLARE @start DATETIME = '2018-04-12 15:53:33' ,
@end DATETIME = '2018-04-13 14:54:32' ,
@x INT;

SET @x = DATEDIFF(s, @start, @end);

SELECT  CONVERT(VARCHAR(10), ( @x / 86400 )) + ' Days '
        + CONVERT(VARCHAR(10), ( ( @x % 86400 ) / 3600 )) + ' Hours '
        + CONVERT(VARCHAR(10), ( ( ( @x % 86400 ) % 3600 ) / 60 ))
        + ' Minutes ' + CONVERT(VARCHAR(10), ( ( ( @x % 86400 ) % 3600 ) % 60 ))
        + ' Seconds';
like image 147
alan Avatar answered Sep 30 '22 13:09

alan