Getting HH:MM:SS value from Seconds

Here is another handy date manipulation function. This one converts the number of seconds, expressed as an int, into the HH:MM:SSS format

SELECT
CASE
WHEN @seconds/3600<10 THEN '0'
ELSE ''
END
+ RTRIM(@seconds/3600)
+
':' + RIGHT('0'+RTRIM((@seconds % 3600) / 60),2)
+
':' + RIGHT('0'+RTRIM((@seconds % 3600) % 60),2)

Rewritten as a function, we have:

CREATE FUNCTION SecToHHMMSS
(
-- Add the parameters for the function here
@seconds INT
)
RETURNS VARCHAR(10)
AS
BEGIN
RETURN
CASE
WHEN @seconds/3600<10 THEN '0'
ELSE ''
END
+ RTRIM(@seconds/3600)
+
':' + RIGHT('0'+RTRIM((@seconds % 3600) / 60),2)
+
':' + RIGHT('0'+RTRIM((@seconds % 3600) % 60),2)
END
GO

This entry was posted in T-SQL. Bookmark the permalink.