Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time difference (in hours) between 2 dates

Tags:

sql

mysql

oracle

I am trying to get the time difference between 2 users, I need the difference in hours.

I tried to use DATEDIFF function but it's wrong.

Here is my code:

SELECT DATEDIFF(*,  
(SELECT max(u1.time_c)
FROM users u)
,
(SELECT max(u2.time_c)
FROM users u2) 
like image 497
Ofer Avatar asked Jun 07 '12 06:06

Ofer


2 Answers

From MySQL DATEDIFF docs:

Only the date parts of the values are used in the calculation.

You will want to look at TIMEDIFF

This will give you the number of hours in the difference in times (assuming your time_c fields are DATETIME or something similar)

SELECT HOUR(TIMEDIFF(  
  (SELECT max(u1.time_c) FROM users u),
  (SELECT max(u2.time_c) FROM users u2)
)) 
like image 53
Matt Dodge Avatar answered Nov 01 '22 01:11

Matt Dodge


You must have a from clause in your select statement. Something like

Select date1 - date2 from dual

returns number of days between date1 and date2.

If you want number of hours:

Select (date1 - date2)*24 from dual;

(this is only for oracle)

like image 26
Florin stands with Ukraine Avatar answered Oct 31 '22 23:10

Florin stands with Ukraine