简体   繁体   中英

Convert HHH:MM:SS to seconds

From the source database, I am getting HH:MM:SS as 832:24:12

Currently I am using below statement which is working fine for most of the cases hh:mm:ss but it fails when hours are more than 99

ISNULL(LEFT(COLUMN,2) * 3600  + RIGHT(LEFT(COLUMN,5),2) * 60 + RIGHT(COLUMN, 2) ,0)

Just another option with a small tweak to your original

Example

Declare @V varchar(50) = '832:24:12'

Select (left(@V,charindex(':',@V)-1)*3600) + (left(right(@V,5),2)*60) + right(@v,2)

Returns

2996652

You can use a tricky solution using PARSENAME() function.

DECALRE @Hours INT = 0, @Minutes INT = 0 , @Seconds INT = 0

SELECT @Hours =  PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),4),
       @Minutes = PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),3),
       @Seconds = PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),2)

SELECT @Hours * 3600  + @Minutes * 60 + @Seconds as TotalSeconds

I am replacing ':' with '.' character after appending dummy sequence of characters ':00' for PARSENAME() function to work by splitting into delimitted data.

For table query

SELECT   PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),4) * 3600 +
         PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),3) * 60 +
         PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),2) As TotalSecs
FROM TableName

This of a guess, however...

CREATE TABLE #Test (TimeString varchar(10))
INSERT INTO #Test
VALUES ('832:24:12')

SELECT TimeString,
       (LEFT(TimeString, H.CI - 1) * 3600) + (SUBSTRING(TimeString,H.CI +1, M.CI - H.CI -1) * 60) + (RIGHT(TimeString, LEN(TimeString) - M.CI))
FROM #Test T
     CROSS APPLY (VALUES(CHARINDEX(':',TimeString))) H(CI)
     CROSS APPLY (VALUES(CHARINDEX(':',TimeString, H.CI+1))) M(CI);

DROP TABLE #Test;

Hours can be the leftwards chars minus 6 positions to take into account the positions for minutes and seconds in the string (:##:##). The minutes can accessed by taking the left 2, of the rightmost 5 chars. The seconds are the right 2 chars.

Ex:

DECLARE @tempval varchar(100) = '832:24:12'

SELECT LEFT(@tempval, LEN(@tempval) - 6) * 3600
      +LEFT(RIGHT(@tempval, 5), 2) * 60
      +RIGHT(@tempval, 2)

Returns

2996652

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM