Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Convert Seconds to hh:mm in SQL

Author  Topic 

AlanPBates
Starting Member

34 Posts

Posted - 2010-05-07 : 15:48:48
How do I convert seconds obtained from a table to hh:mm format in a query ?


Thanks,

Alan

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-05-07 : 16:08:51
Divide by 3600 to get hours, and then use modulus function (%) to get the remainder which is minutes.

Here's an example with 7201 seconds:
declare @s int
set @s = 7201
select RIGHT('00' + CONVERT(varchar(2), @s/3600), 2) + ':' + RIGHT('00' + CONVERT(varchar(2), @s%3600), 2)


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

AlanPBates
Starting Member

34 Posts

Posted - 2010-05-07 : 16:11:03

Thanks Tara ..
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-05-07 : 16:14:59
You're welcome, glad to help.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2010-05-07 : 18:05:51
[code]declare @seconds int
set @seconds = 18422
select [HH:MM] = convert(varchar(5),dateadd(ss,@seconds,0),108)[/code]
Results:[code]HH:MM
-----
05:07[/code]

CODO ERGO SUM
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-05-07 : 18:08:17
I didn't realize you could do that with data being in seconds. It makes sense now that I see it though.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2010-05-07 : 19:13:04
The OP didn't really say what they wanted to do with leftover seconds. The solution I posted just discards them, but you could do regular rounding by adding 30 to the total number of seconds.

I assumed the time will not be >= 86400 (24 hours). If it is, there would have to be some adjustment.



CODO ERGO SUM
Go to Top of Page
   

- Advertisement -