SQL Convert Seconds into Day:Hour:Min:Sec

萝らか妹 提交于 2019-12-11 16:34:53

问题


Topic says it all. I'm trying to do some magic, via a function, that turns a second integer into a string "DD:HH:MM:SS".

Snip

input: 278543
output: "3D 5H 22M 23S "

What I'd like to do, more gracefully if possible, is pad the numbers (So that 5M shows as 05M) and right align them so that "3D 5H 22M 23S " is " 3D 5H 22M 23S" instead.

edit: Latest cut that seems to work. Would love to have it prettier, but this definitely works as far as I can tell:

CREATE FUNCTION DHMS(secondsElapsed INT)
RETURNS Char(20)
LANGUAGE SQL
NO EXTERNAL ACTION
DETERMINISTIC

BEGIN
    DECLARE Dy Integer;
    DECLARE Hr Integer;
    DECLARE Mn Integer;
    DECLARE Sc Integer;

    SET Dy = Cast(     secondsElapsed / 86400         as Int);
    SET Hr = Cast(MOD( secondsElapsed, 86400 ) / 3600 as Int);
    SET Mn = Cast(MOD( secondsElapsed, 3600 ) / 60    as Int);
    SET Sc = Cast(MOD( secondsElapsed, 60 )           as Int); 

     RETURN REPEAT(' ',6-LENGTH(RTRIM(CAST(Dy AS CHAR(6))))) || Dy || 'D ' 
         || REPEAT('0',2-LENGTH(RTRIM(CAST(Hr AS CHAR(6))))) || Hr || 'H ' 
         || REPEAT('0',2-LENGTH(RTRIM(CAST(Mn AS CHAR(6))))) || Mn || 'M '
         || REPEAT('0',2-LENGTH(RTRIM(CAST(Sc AS CHAR(6))))) || Sc || 'S';
END

回答1:


You were on the right track using LPAD(), since it can pad with zero or any other string. CHAR(15) is not enough to format the output the way you want and still allow five positions for the number of days, which is the length you specified in your code.

CREATE OR REPLACE FUNCTION DHMS(secondsElapsed INT)
RETURNS Char(18)
LANGUAGE SQL
NO EXTERNAL ACTION
DETERMINISTIC

RETURN LPAD( secondsElapsed / 86400 , 5 ) || 'D ' 
  || LPAD( MOD( secondsElapsed, 86400 ) / 3600, 2, '0') || 'H ' 
  || LPAD( MOD( secondsElapsed, 3600 ) / 60, 2, '0' ) || 'M '
  || LPAD( MOD( secondsElapsed, 60 ), 2, '0' ) || 'S'
;



回答2:


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



来源:https://stackoverflow.com/questions/4694864/sql-convert-seconds-into-dayhourminsec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!