SQL Server Convert HH:mm:ss String into Time Data Type, the Total Number of Minutes, or the Total Nmber of Seconds.
In this post, we will demonstrate the conversion of a HH:mm:ss time string into a time data type, and then it calculates and displays the total number of minutes and seconds since midnight for that converted time. It's a useful example for working with time-related calculations involving seconds in SQL Server's T-SQL.
Convert String to Time Type, Minutes, and Seconds
You can use this Fiddle to follow along and practice converting string to
time, minutes, or seconds
DECLARE @timeString VARCHAR(8) = '10:32:59';
DECLARE @time TIME = CONVERT(TIME, @timeString);
SELECT @time AS Time
,DATEDIFF(MINUTE, CAST('00:00' AS TIME), @time) AS NumOfMins
,DATEDIFF(SECOND, CAST('00:00' AS TIME), @time) AS NumOfSeconds;
Query Result
| Time | NumOfMins | NumOfSeconds |
|---|---|---|
| 10:32:59.0000000 | 632 | 37979 |
Here is an explanation of the above code snippet:
-
DECLARE @timeString VARCHAR(8) = '10:32:59';declares a variable named@timeStringand assigns the value'10:32:59'to it. This variable now holds the input time string in the format HH:mm:ss. -
DECLARE @time TIME = CONVERT(TIME, @timeString);declares another variable named@timeand assigns it the value obtained by converting the@timeStringvariable into a time data type. This step converts the input time string into a valid time value that includes hours, minutes, and seconds. -
SELECT @time AS TIME, DATEDIFF(MINUTE, CAST('00:00' AS TIME), @time) AS NumOfMins, DATEDIFF(SECOND, CAST('00:00' AS TIME), @time) AS NumOfSeconds;performs aSELECTquery with similar columns as before:- The
@timevariable value is displayed under the column nameTime, representing the time value that was converted from the input time string. DATEDIFF(MINUTE, CAST('00:00' AS TIME), @time)calculates the difference in minutes between midnight ('00:00') and the value stored in the@timevariable. This provides the total number of minutes since midnight.DATEDIFF(SECOND, CAST('00:00' AS TIME), @time)calculates the difference in seconds between midnight ('00:00') and the value stored in the@timevariable. This gives the total number of seconds since midnight.
- The