I already have a string to calculate the difference in hours between 2 dates which I'd got from stack:
24 * (to_date(to_char(stp.created_date,'YYYY-MM-DD hh24:mi:ss'),'YYYY-MM-DD hh24:mi:ss') -
(to_date(to_char(adhh.created_date,'YYYY-MM-DD hh24:mi:ss'),'YYYY-MM-DD hh24:mi:ss'))) diff_hours
But I want to see this as HH:MM:SS
Here's 2 dates/times as example: STP date 26-Feb-18 12.59.21 ADHH date 26-Feb-18 12.59.32
So I want it to say difference is 00:00:11 (11 seconds)
at the moment I get the result as -0.003 hours
Thanks in advance as always
I will suggest you small change in your query
just replace 'x' in above query with your result column
hope this helps..
Assuming the columns are already dates, and the therefore the conversion to and from strings you are doing is pointless, and that the difference is always going to be less than a day, you could do:
This gets the difference between the dates as a fraction of a day; makes sure it's positive via
abs()
; and then adds that fraction back on to a nominal date, which has its time as midnight. Then it converts that to a string, looking only at the time.Quick demo:
If the difference can exceed a day, but not a year, you could change the format model to something like
'FMDDD FMHH24:MI:SS'
, which will show full days at the start.You can convert it to an interval and then just use
TO_CHAR
to convert the interval to a string:SQL Fiddle
Oracle 11g R2 Schema Setup:
Query 1:
Results:
Query 2: If you do not have a days component (i.e. the dates are always less than 24 hours apart) then just replace the
0
substring:Results:
It looks like your columns are already in
DATE
format (they should be!). In that case you can just get the difference between the dates as aDAY TO SECOND INTERVAL
. Use theNUMTODSINTERVAL
function for that. Then using theEXTRACT
function, you can get the interval in terms of hours, minutes and seconds.Here is a sample query.
Here is the result.
DIFF_HOURS
00:00:11
Assuming the columns are already
DATE
values (if not, I strongly recommend to change it) you can convert them to timestamp. It should be sufficient to convert only one value, but of course you can convert both.Result is a
INTERVAL DAY TO SECOND
value which has fixed output format ofDDD HH:MI:SS.FF
. In order to get desired format you can useNote, TO_CHAR does not work for intervals. Thus you have to use REGEXP or extract components with EXTRACT(... FROM ...)