简体   繁体   English

Oracle:以特定格式计算两个日期之间的持续时间

[英]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 我想计算两个日期(时间戳)之间的差异,但要使用诸如DDd HH24:MI:SS.FF的特定格式

As an example : 2d 10:25:30.350 例如: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 谢谢

SQL Fiddle SQL小提琴

Oracle 11g R2 Schema Setup : Oracle 11g R2架构设置

Query 1 : 查询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 |

If you know that you will never have more than 365 days, you can use a valid date and only print the numbers. 如果您知道自己永远不会超过365天,则可以使用有效日期,仅打印数字。 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. 如果需要的话,删除前导零非常容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM