tags:

views:

487

answers:

4

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.

+4  A: 

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.

Rob
I selected this answer because it's short, consise, easy to read. Upvotes for all answers--they all work! Thanks everyone
Jeff
+6  A: 

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

OMG Ponies
+3  A: 

You could convert the dates to timestamps and use native functionality to get the individual components out...

SELECT EXTRACT( DAY    FROM ( end_timestamp - start_timestamp ) )   days
     , EXTRACT( HOUR   FROM ( end_timestamp - start_timestamp ) )   hours
     , EXTRACT( MINUTE FROM ( end_timestamp - start_timestamp ) )   minutes
     , EXTRACT( SECOND FROM ( end_timestamp - start_timestamp ) )   seconds
  FROM ( SELECT TO_TIMESTAMP( TO_CHAR( start_date, 'DD/MM/YYYY HH24:MI:SS' )
                            , 'DD/MM/YYYY HH24:MI:SS' )   start_timestamp
              , TO_TIMESTAMP( TO_CHAR( end_date, 'DD/MM/YYYY HH24:MI:SS' )
                            , 'DD/MM/YYYY HH24:MI:SS' )   end_timestamp
           FROM ( SELECT TO_DATE( '01/10/2009 14:25:01'
                                , 'DD/MM/YYYY HH24:MI:SS' )   start_date
                       , TO_DATE( '03/10/2009 23:09:15'
                                , 'DD/MM/YYYY HH24:MI:SS' )   end_date
                    FROM dual
                )
       )
Paul James
+3  A: 

Why not just convert to timestamp and implicitly use an interval day to second data type?

select to_timestamp(sysdate+1.1234) - to_timestamp(sysdate) diff
from dual
/

DIFF        
----------- 
1 2:57:42.0
David Aldridge