Solved

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

Posted on 2010-11-14
4
433 Views
Last Modified: 2012-05-10
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
Comment
Question by:countrymeister
  • 2
4 Comments
 
LVL 69

Expert Comment

by:Qlemo
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

by:James Murrell
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,  
    DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh, @date1, @date2),@date1),@date2) as Minutes_Difference

0
 
LVL 69

Accepted Solution

by:
Qlemo earned 150 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

by:cyberkiwi
cyberkiwi earned 100 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Suggested Solutions

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question