Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two dates in exact number of hours in SQL

I would like to calculate the exact hours difference between two datetime variables. The hours difference should be exact like this:

1.5
2
6.25

Anybody please help out..Thanks in advance...

like image 553
prabu R Avatar asked Feb 05 '13 10:02

prabu R


People also ask

How do I find the difference between two dates and hours in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

How do you find the difference between two dates in hours?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.

How can I find the difference between two timestamps in SQL?

{fn TIMESTAMPDIFF(interval,startDate,endDate)} returns the difference between the starting and ending timestamps (startDate minus endDate) for the specified date part interval (seconds, days, weeks, and so on). The function returns an INTEGER value representing the number of intervals between the two timestamps.

How do I subtract hours from a date in SQL?

MySQL SUBTIME() Function The SUBTIME() function subtracts time from a time/datetime expression and then returns the new time/datetime.


2 Answers

You could use DATEDIFF to find the difference in minutes and convert that into hours:

select datediff(mi, startdate, enddate)

Assuming 1.5 means 1 hour and 30 minutes you could simply divide the result by 60:

select datediff(mi, startdate, enddate) / 60.0
like image 130
Daniel Kelley Avatar answered Oct 25 '22 16:10

Daniel Kelley


Keep it simple:

declare @date1 datetime
declare @date2 datetime

select @date1 = GETDATE();
select @date2 = '2013-02-02 14:05'

select DATEDIFF(hh, @date2, @date1)


Results
-----------
71

(1 row(s) affected)
like image 27
Philip Wade Avatar answered Oct 25 '22 14:10

Philip Wade