SQL Server Admin
T-SQL Articles

March 30, 2008

How to Convert Seconds to HH:MM:SS




If you have a column that contains time in seconds and want to convert it to an hour : minute: seconds format, use this query. This query also takes care of displaying hours > 23.


DECLARE @SecondsToConvert int
SET @SecondsToConvert = 10000

-- Declare variables
DECLARE @Hours int
DECLARE @Minutes int
DECLARE @Seconds int
DECLARE @Time datetime

-- Set the calculations for hour, minute and second
SET @Hours = @SecondsToConvert/3600
SET @Minutes = (@SecondsToConvert % 3600) / 60
SET @Seconds = @SecondsToConvert % 60

-- Store the datetime information retrieved in the @Time variable
SET @Time = (SELECT
RTRIM(CONVERT(char(8), @Hours) ) + ':' +
CONVERT(char(2), @Minutes) + ':' +
CONVERT(char(2), @Seconds));

-- Display the @Time variable in the format of HH:MM:SS
SELECT CONVERT(varchar(8),CONVERT(datetime,@Time),108)


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

3 Responses to "How to Convert Seconds to HH:MM:SS"
  1. Anonymous said...
    June 16, 2008 10:46 AM

    The query does not work for seconds >= 86400 (24 hours or more).

    Is there anyway to 36:15:00 (36 hours and 15 minutes)?

  2. Anonymous said...
    July 8, 2011 12:25 PM

    Excellent work! Many thanks.

  3. Anonymous said...
    May 4, 2012 10:49 AM

    How to convert seconds(Int) to Time more than 86400.
    like 45:38:15 (HH:mm:ss)

 

Copyright © 2009-2012 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions