kkung
kkung

Reputation: 743

Oracle : calculate duration between two dates in specific format

I would like to calculate the differnce between two dates (timestamp) but in a specific format like DDd HH24:MI:SS.FF

As an example : 2d 10:25:30.350

There many examples on the net but most of them separate the days, hours, minutes.. in differents columns and not getting all of them in one column

Thanks

Upvotes: 0

Views: 304

Answers (2)

MT0
MT0

Reputation: 168806

SQL Fiddle

Oracle 11g R2 Schema Setup:

Query 1:

WITH times ( start_time, end_time ) AS (
  SELECT TIMESTAMP '2015-01-01 00:00:00', TIMESTAMP '2015-01-03 10:25:30.350' FROM DUAL
  UNION ALL
  SELECT TIMESTAMP '2015-01-01 00:00:00', TIMESTAMP '2015-01-01 09:00:00.000607' FROM DUAL
  UNION ALL
  SELECT TIMESTAMP '2015-03-01 00:00:00', TIMESTAMP '2016-03-01 00:00:00' FROM DUAL
  UNION ALL
  SELECT TIMESTAMP '2015-01-01 00:00:00', TIMESTAMP '2016-01-11 00:00:00' FROM DUAL
)
SELECT TO_CHAR( start_time, 'YYYY-MM-DD HH24:MI:SS.FF6' ) AS start_time,
       TO_CHAR( end_time, 'YYYY-MM-DD HH24:MI:SS.FF6' ) AS end_time,
       REGEXP_REPLACE( end_time - start_time, '^[+-]0*(\d+) 0?(\d+:\d{2}:\d{2}\.\d{3}\d*?)0*$', '\1d \2' ) AS time_difference
FROM   times

Results:

|                 START_TIME |                   END_TIME |   TIME_DIFFERENCE |
|----------------------------|----------------------------|-------------------|
| 2015-01-01 00:00:00.000000 | 2015-01-03 10:25:30.350000 |   2d 10:25:30.350 |
| 2015-01-01 00:00:00.000000 | 2015-01-01 09:00:00.000607 | 0d 9:00:00.000607 |
| 2015-03-01 00:00:00.000000 | 2016-03-01 00:00:00.000000 |  366d 0:00:00.000 |
| 2015-01-01 00:00:00.000000 | 2016-01-11 00:00:00.000000 |  375d 0:00:00.000 |

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1271231

If you know that you will never have more than 365 days, you can use a valid date and only print the numbers. I'm thinking of something like this:

select (case when ts1 - ts2 < 1
             then '000d ' || to_char(date '2000-01-01' + (t1 - t2), 'HH24:MI:SS')
             else to_char(date '2000-01-01' + (t1 - t2) - 1, 'DDDd HH24:MI:SS')
        end)

This does zero-pad the day component. It is easy enough to remove the leading zeros if that is desired.

Upvotes: 0

Related Questions