Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Date Subtraction

How would i write an expression that gives me the difference between two dates in days, hours, minutes, seconds, etc? By default subtracting two dates in oracle returns days as a decmial.

like image 875
Jeff Avatar asked Nov 25 '25 23:11

Jeff


2 Answers

Use:

SELECT TO_CHAR(date1,'MMDDYYYY:HH24:MI:SS') date1,
       TO_CHAR(date2,'MMDDYYYY:HH24:MI:SS') date2,
       TRUNC(86400*(date2-date1)) - 60*(TRUNC((86400*(date2-date1))/60)) seconds,
       TRUNC((86400*(date2-date1))/60) - 60*(TRUNC(((86400*(date2-date1))/60)/60)) minutes,
       TRUNC(((86400*(date2-date1))/60)/60) - 24*(TRUNC((((86400*(date2-date1))/60)/60)/24)) hours,
       TRUNC((((86400*(date2-date1))/60)/60)/24) days,
       TRUNC(((((86400*(date2-date1))/60)/60)/24)/7) weeks
  FROM TABLE

Reference: A Comparison of Oracle's DATE and TIMESTAMP Datatypes

like image 80
OMG Ponies Avatar answered Nov 28 '25 16:11

OMG Ponies


That decimal is the number of days difference between the two dates provided. You can do a little math to convert that to days, hours, minutes, seconds, etc.

EDIT: I see what you're looking for. I'm sure there's an easier way, but I would probably accomplish it thusly:

select trunc(5.3574585) days, 
       trunc(mod((5.3574585) * 24, 24)) hours, 
       trunc(mod((5.3574585) * 24 * 60, 60)) minutes, 
       trunc(mod((5.3574585) * 24 * 60 * 60, 60)) seconds 
  from dual;

...where 5.3574585 is the number of days returned by the subtraction...

Note: this isn't really tested, it's off the top of my head.

like image 33
Rob Avatar answered Nov 28 '25 14:11

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!