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...
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.
To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.
{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.
MySQL SUBTIME() Function The SUBTIME() function subtracts time from a time/datetime expression and then returns the new time/datetime.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With