tags:

views:

12986

answers:

3

Hi,

I have a table as follows:

Filename - varchar Creation Date - Date format dd/mm/yyyy hh24:mi:ss Oldest cdr date - Date format dd/mm/yyyy hh24:mi:ss

How can I calcuate the difference in hours minutes and seconds (and possibly days) between the two dates in Oracle SQL?

Thanks

+7  A: 

You can substract dates in Oracle. This will give you the difference in days. Multiply by 24 to get hours, and so on.

SQL> select oldest - creation from my_table;

If your date is stored as character data, you have to convert it to a date type first.

SQL> select 24 * (to_date('2009-07-07 22:00', 'YYYY-MM-DD hh24:mi') 
             - to_date('2009-07-07 19:30', 'YYYY-MM-DD hh24:mi')) diff_hours 
       from dual;

DIFF_HOURS
----------
       2.5
Thilo
A: 

You could use to_timestamp function to convert the dates to timestamps and perform a substract operation.

Something like:

select to_timestamp ('13.10.1990 00:00:00','DD.MM.YYYY HH24:MI:SS') - TO_TIMESTAMP ('01.01.1990:00:10:00','DD.MM.YYYY:HH24:MI:SS')from dual
HyLian
what units would this give? hours? milliseconds? slivers?
skaffman
I have tried both the to_date and to_timestamp and both give me an answer in days, rounded down so if the difference is 1 hour I receive an answer of 0, multiplying this by 24 gives 0. I do receive the correct answer if I type in the date time but I can't do this for 25m rows. Any thoughts?
Steve
Using a substraction between timestamps it would return you another timestamp in a format like "DAYS HOUR:MINS:SECS.milisecs". You could trunc this to get the value you need
HyLian
Subtraction between timestamps returns an INTERVAL datatype. You can use the EXTRACT function to return various parts of an intervalegselect extract(hour from (timestamp '2009-12-31 14:00:00' - timestamp '2009-12-31 12:15:00')) hr from dual;Note: That only shows the HOUR part, so if the difference is 1 day and 1 hour, this will show 1 not 25.
Gary
A: 

$sql="select bsp_bp,user_name,status,to_char(ins_date,'dd/mm/yyyy hh12:mi:ss AM'),to_char(pickup_date,'dd/mm/yyyy hh12:mi:ss AM'),trunc((pickup_date-ins_date)2460*60,2),message,status_message from valid_bsp_req where id >= '$id'";

with regards sujan