Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the difference in hours between two dates?

Tags:

oracle

I have to do a "select" that returns the difference between a field of type date from the database and the current date in hours. How can I do this in oracle?

I try this:

   select 24 * (to_date(sysdate, 'YYYY-MM-DD hh24:mi') 
         - to_date('2012-02-28 15:20', 'YYYY-MM-DD hh24:mi')) diff_hours 
   from dual;

But that did not work.

like image 811
Guilherme Costa Avatar asked Feb 28 '12 19:02

Guilherme Costa


2 Answers

The error is because SYSDATE is already a date, there's no need to use TO_DATE() to convert it to a date.

If you don't convert it to a date:

select
    24 * (sysdate - to_date('2012-02-28 15:20', 'YYYY-MM-DD hh24:mi')) as diff_hours
from dual;

And if the formatting of the dates are wrong, you can possible use two steps like:

select
    24 * (to_date(to_char(sysdate, 'YYYY-MM-DD hh24:mi'), 'YYYY-MM-DD hh24:mi') - to_date('2012-02-28 15:20', 'YYYY-MM-DD hh24:mi')) as diff_hours
from dual;
like image 129
aweis Avatar answered Oct 19 '22 18:10

aweis


Diference between two dates in hours and minutes

SELECT     TRUNC(minutes_ / 60) || ' Hours, ' || TRUNC(MOD(minutes_,  60)) || ' Minutes'  diference
FROM     ( SELECT  (sysdate - to_date('16/10/2019 18:45:00', 'DD/MM/YYYY HH24:MI:SS')) * 24 * 60     AS minutes_
  FROM     dual
);

Diference between two dates in hours

SELECT     ROUND(minutes_ / 60, 2) || ' Hours ' 
FROM     ( SELECT  (sysdate - to_date('16/10/2019 18:45:00', 'DD/MM/YYYY HH24:MI:SS')) * 24 * 60     AS minutes_
  FROM     dual
);

Diference between two dates in hours (truncate)

SELECT     ROUND(minutes_ / 60, 2) || ' Hours ' 
FROM     ( SELECT  (sysdate - to_date('16/10/2019 18:45:00', 'DD/MM/YYYY HH24:MI:SS')) * 24 * 60     AS minutes_
  FROM     dual
);
like image 35
Geysa O. Marinho Avatar answered Oct 19 '22 18:10

Geysa O. Marinho