Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to Convert Varchar HH:MM to Integer Minutes in SQL Server 2008

I am having a table in SQL Server where there is a column name TimeSpent Datatype Varchar(25). It basically stores Time as HH:MM Format. As per the requirement now i want that it gives me actual timespent in Minutes i.e. 01:00 gives me 60, 01:30 -> 90. Please help me to write the query in SQL Server 2008 , so that will convert Varchar (HH:MM) into Minutes(integer).

like image 302
Dharmendra Kumar Singh Avatar asked Mar 21 '13 04:03

Dharmendra Kumar Singh


People also ask

How do I convert time to INT in SQL?

Assuming you are looking for the "time" analogy to the "date" portion of your code which takes YYYYMMDD and turns it into an INT , you can: start with the HH:mm:ss format given by the style number 108. remove the colons to get that string into HHmmss. then convert that to INT.

How do I convert varchar to numeric in SQL?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.


2 Answers

Try

SELECT LTRIM(DATEDIFF(MINUTE, 0, TimeSpent)) 
  FROM yourtable

Given

| TIMESPENT |
-------------
|     00:12 |
|     01:05 |
|     10:00 |

Output:

| MINUTES |
-----------
|      12 |
|      65 |
|     600 |

Here is SQLFiddle

like image 89
peterm Avatar answered Oct 06 '22 11:10

peterm


This will solve your issue. Please refer to SQLFiddle


select cast(left(TimeSpent, charindex(':',TimeSpent,0)-1) as int)*60+
       cast(right(TimeSpent, len(TimeSpent)-charindex(':',TimeSpent, 0)) as int)
from test
like image 35
ljh Avatar answered Oct 06 '22 10:10

ljh