SQL - Seconds to Day, Hour, Minute, Second [duplic

2019-02-19 23:44发布

问题:

Possible Duplicate:
Efficient way to convert second to minute and seconds in sql server 2005

I have a query which needs to return the second in Day, Hour, Minute, Second format.

The below code works fine when its less than a day, but does not work, when the value in second is greater than a day

PRINT Convert(VarChar, DateAdd(S, 86400, 0), 108)

86400 is exactly a day and it returns 00:00:00

Can someone modify it and show me the result something like this

1:00:00:00.

Thanks

回答1:

How about this:

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

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


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

Result -- 170:20:40:00

See SQL Fiddle with Demo



回答2:

try this:

declare @seconds int=87500;

select cast(@seconds/86400 as varchar(50))+':'+
  Convert(VarChar, DateAdd(S, @seconds, 0), 108) 

Result:

1:00:18:20