Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Format seconds as HH:MM:SS time

Is there any tricky way to format seconds like hours:minutes:seconds. For example,

3660

seconds will be displayed as

01h 01m 00s

or

01:01:00

I am aware of the standard way of doing this:

  1. Divide all seconds on 3600 to get the hours
  2. Divide the rest seconds on 60 to get the minutes
  3. The rest are the seconds

I met the following issues:

  1. I am not able to create separate function that do this.

  2. My code is in view using several CTEs. So, variables can be declare using the CTEs only.

  3. I am not able to use the standard solution because I will have results bigger then one day - How to convert Seconds to HH:MM:SS using T-SQL
like image 263
gotqn Avatar asked Nov 01 '12 12:11

gotqn


2 Answers

SELECT RIGHT('00'+CONVERT(VARCHAR(10),Seconds/3600),2)  
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),(Seconds%3600)/60),2) 
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),Seconds%60),2) AS [HH:MM:SS] 
FROM table1

Result:

HH:MM:SS
01:01:00
01:03:20
01:10:00
00:10:00
00:01:00
00:00:30
24:00:00
24:06:40

See this SQLFiddle

like image 108
Himanshu Jansari Avatar answered Nov 10 '22 20:11

Himanshu Jansari


Try this:

SELECT CONVERT(TIME(0), DATEADD(SS,***seconds***,0),108) as 'FieldName'

will return HH:MM:SS

Example:

46800 seconds = 1:00 PM

FieldName = 13:00:00

Hope this helps.

like image 8
Greg Avatar answered Nov 10 '22 22:11

Greg