Convert HH:MM:SS string to number of minutes

后端 未结 8 618
醉梦人生
醉梦人生 2021-01-22 12:03

I have the below query.

select cast(dateadd(minute, datediff(minute, TimeIn, TimeOut), 0) as time(0) )

I get the results from two columns in th

8条回答
  •  被撕碎了的回忆
    2021-01-22 12:42

    Unfortunately, if you want to use DATEPART function for values with more than 24 hours, you will receive an error:

    Conversion failed when converting date and/or time from character string."

    You can test it with this code:

    declare @Time DATETIME = '32:00:00'
    select ((DATEPART(HOUR, @Time)*60) + (DATEPART(MINUTE, @Time)))
    

    To solve this, I worked with this another approach:

    declare @tbl table(WorkHrs VARCHAR(8))
    insert into @tbl(WorkHrs) values ('02:47:00')
    insert into @tbl(WorkHrs) values ('32:00:00')
    -- Sum in minutes
    SELECT TRY_CAST(([HOURS] * 60) + [MINUTES] + ([SECOND] / 60) AS INT) as TotalInMinutes
    FROM (
    SELECT 
        -- Use this aproach to get separated values 
        SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
        SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
        SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND] -- probably you can ignore this one
        FROM @tbl
    )
    tbl
    -- Sum in seconds
        SELECT TRY_CAST(([HOURS] * 3600) + ([MINUTES] * 60) + [SECOND] AS INT) as TotalInSeconds
        FROM (
        SELECT 
        -- Use this aproach to get separated values 
        SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
        SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
        SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND]
        FROM @tbl
    )
    tbl
    

    This code will return like this:

提交回复
热议问题