Expiring Todayâ€”Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# How to find number of hours between two datetime fields in SQL server

Posted on 2010-11-14
Medium Priority
448 Views
I have two datetimestamp fields  dt1 and dt2
I need to find the difference in hours between dt1 and dt2 in SQL Server

e.g
dt1 = 2010-11-14 13:00:00.000
dt2 = 2010-11-14  15:00:00.000
result is 2 hours

dt1 = 2010-11-13 13:00:00.000
dt2 = 2010-11-14  15:00:00.000
result is 26 hours

dt1 = 2010-11-14 13:00:00.000
dt2 = 2010-11-14  15:30:00.000
result is 2.5 hours
0
Question by:countrymeister
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 71

Expert Comment

ID: 34132350
Depending on the resolution you need, you can do  simple calculation:

select (dt2-dt1)*24
or
select datediff(mi, dt1, dt2)/60.0
or the like.
0

LVL 31

Expert Comment

ID: 34132357
You want the DATEDIFF function:

SELECT DATEDIFF(hh, @date1, @date2)

if you want minutes as well
select DATEDIFF(hh, @date1, @date2) as Hours_Difference,

0

LVL 71

Accepted Solution

Qlemo earned 600 total points
ID: 34132362
Sorry, the first one is not correct, we need to convert it to float:

select convert(float, dt2-dt1) * 24

dt2-dt1 results in a datetime representing the difference between both dates. Converting to float it is expressed as fractions of days, so multiplying with 24 (hours per day) makes it fractions of hours.
0

LVL 58

Assisted Solution

cyberkiwi earned 400 total points
ID: 34132366
the first form from qlemo doesn't work in sql server
2nd one does, but depending on precision, you could also use

datediff(ss, dt1, dt2) / 3600.0

or
round((convert(float,d2)-convert(float,d1))*24,5)
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includâ€¦
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Viewers will learn how the fundamental information of how to create a table.
###### Suggested Courses
Course of the Month11 days, 4 hours left to enroll