我想计算两个日期(时间戳)之间的差异但是 以DDd HH24:MI:SS.FF
的特定格式例如:2d 10:25:30.350
网上有很多例子,但是大多数例子都将天数,小时数,分钟数分开,在不同的列中,而不是将它们全部放在一列中
由于
答案 0 :(得分:1)
Oracle 11g R2架构设置:
查询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 |
答案 1 :(得分:0)
如果您知道自己永远不会超过365天,则可以使用有效日期并仅打印数字。我想到这样的事情:
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)
这会对日期组件进行零填充。如果需要,很容易删除前导零。