将秒数转换为总小时数:分钟:秒

时间:2014-06-27 19:22:46

标签: sql tsql sql-server-2008-r2

有人可以指导我如何将秒转换为总小时,分钟和秒格式吗?

例如:2,652,819秒应该给736:53:39

我能够以days:hours:minutes:seconds格式获得相同但我特别要求将天数转换为总小时数

3 个答案:

答案 0 :(得分:2)

假设您已获得tot_secs的整数值 - 浮点数需要明智地使用round()ceil()和/或floor(),但是您可以尝试这样的事情:

select hours    = ( t.tot_secs / 3600 )      , -- hours   is total seconds / (secs/hr)
       minutes  = ( t.tot_secs % 3600 ) / 60 , -- minutes is whatever's left over / 60
       seconds  =   t.tot_secs % 60 , -- whatever's left over is seconds
       hh_mm_ss =                    convert(varchar,   t.tot_secs / 3600 )
                + ':' + right( '0' + convert(varchar, ( t.tot_secs % 3600 ) / 60 ) , 2 )
                + ':' + right( '0' + convert(varchar,   t.tot_secs          % 60 ) , 2 )
from ( select tot_secs = 2652819
     ) t

以上查询产生

hours minutes seconds hh_mm_ss
----- ------- ------- --------
 736     53      39   736:53:39

答案 1 :(得分:0)

这有效:

DECLARE @Seconds INT
SET @Seconds = 2652819 

SELECT  CAST(@Seconds/3600 AS VARCHAR(10)) + ':' +
        CAST((@Seconds%3600)/60 AS VARCHAR(10)) + ':' + 
        CAST(@Seconds%60 AS VARCHAR(2))

答案 2 :(得分:0)

这会将秒解析为几天:小时:分钟:秒。

declare @seconds int = 2652819 
select @seconds / (60 * 60 * 24) [days], (@seconds / (60 * 60)) % 60 [hours], (@seconds / 60) % 60 [minutes], @seconds % 60 seconds
select cast(@seconds / (60 * 60 * 24) as varchar(10)) + ':' + 
       cast((@seconds / (60 * 60)) % 60 as varchar(2))  + ':' + 
       cast((@seconds / 60) % 60 as varchar(2)) + ':' +
       cast(@seconds % 60 as varchar(2)) as [days:hours:minutes:seconds]

输出:

days|hours|minutes|seconds
----|-----|-------|-------
30  | 16  |  53   |  39

days:hours:minutes:seconds
--------------------------
30:16:53:39