Dharmendra Kumar Singh
Dharmendra Kumar Singh

Reputation: 2991

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).

Upvotes: 6

Views: 58155

Answers (3)

Michal Bolehradsky
Michal Bolehradsky

Reputation: 11

SELECT top 1 (substring(CONVERT(VARCHAR(5), TimeSpent, 108), 1, 2) * 60 + substring(CONVERT(VARCHAR(5), TimeSpent, 108), 4, 2)) as minutes from test

Upvotes: 0

ljh
ljh

Reputation: 2594

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

Upvotes: 2

peterm
peterm

Reputation: 92785

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

Upvotes: 16

Related Questions