Wednesday, July 5, 2017

Time in 00:00:00 text format with the need to convert it to seconds then back

This is just a quick example of converting a text format "time" field back and forth into seconds so that summations and such can be done.

DECLARE @fauxTime VARCHAR(8) = '00:01:00'; -- we have a free form "time" field
DECLARE @fauxTimeInSeconds INT = (SELECT Datediff(second, Cast('00:00:00' AS TIME), Cast(@fauxTime AS TIME))) -- Convert it to seconds\
DECLARE @fauxTimeBackToTimefromSeconds TIME =(SELECT Cast(CONVERT(VARCHAR, Dateadd(ss, @fauxTimeInSeconds, 0), 108) AS TIME))
DECLARE @fauxTimeBackToHHMMSSfromSeconds VARCHAR(8) =(SELECT CONVERT(VARCHAR,Dateadd(ss, @fauxTimeInSeconds, 0), 108)) -- convert back to a character based time field
PRINT @fauxTime

PRINT @fauxTimeInSeconds

PRINT @fauxTimeBackToTimefromSeconds

PRINT @fauxTimeBackToHHMMSSfromSeconds

OUTPUT:
00:01:00 -- Original.
60 -- Converted to seconds.
00:01:00.0000000 -- Converted back into a time field.
00:01:00 - Converted back to a character field.

No comments:

Post a Comment