Click here to Skip to main content
15,917,971 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I have two nvarchar fields with time data 12:34:34 and the second one 12:34 I want to calculate the difference in Hours. The first field is called (OTIM) the second field is called (ReportedTime) if the name matters. Some one please help me. I tried substring to trim the OTIM, I am unable to make it work.
Posted
Comments
[no name] 19-Sep-14 16:43pm    
http://www.sqlines.com/sql-server/functions/datediff

SQL
-- With Specified time

SELECT DATEDIFF(mi, '12:34:34', '12:34')/60;


-- with Specified Column Names
SELECT DATEDIFF(mi, OTIM, ReportedTime)/60;



Thanks,
Baliram Suryawanshi
 
Share this answer
 
v2
Comments
Member 8211588 19-Sep-14 17:07pm    
I get the following error:

Conversion failed when converting date and/or time from character string.
Baliram Suryawanshi 20-Sep-14 0:58am    
Execute below statement with hard coded time:
-- With Specified time

SELECT DATEDIFF(mi, '12:34:34', '12:34')/60;

It should not give any error. It works with SQL server 2012 as well.


If you are getting error in the scripts when you execute it with column names then it must be due to invalid data available in your column. With invalid I mean non-datetime data.
If it is case, first try to convert the invalid data in Time.
try

SELECT DATEDIFF(HOUR, CAST(OTIM AS DATETIME),CAST(ReportedTime AS DATETIME)) FROM YourTableName


If you are using SQL server 2005/2008 then this will work, I did not test in other versions
 
Share this answer
 
Comments
Member 8211588 19-Sep-14 17:05pm    
Hi I am using sql 2012 and when I tried your code, I got the following error:
Conversion failed when converting date and/or time from character string.
Abdul Samad KP 19-Sep-14 17:18pm    
Sorry I don’t have a sql2012 installed on my machine to test, but I think it will work if the time format is hh:mm:ss or hh:mm. Please check all rows are having values in this format.
Never store time data in string attributes. Use appropriate date/time SQL data types, just as DATE.
—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900