减去两个日期得到hh:mm:ss

时间:2014-02-18 20:46:50

标签: oracle

我正在尝试减去事件的结束-START事件的结束并获得时差。我开始尝试:

TO_CHAR(WXN_MOPACTIVITY.MOPEND, 'YYYY-MM-DD HH24:MI:SS') - TO_CHAR(WXN_MOPACTIVITY.MOPSTART, 'YYYY-MM-DD HH24:MI:SS') AS TIME_DIF

然而,这不起作用。然后我尝试了:

(WXN_MOPACTIVITY.MOPEND - WXN_MOPACTIVITY.MOPSTART) AS TIME_DIF

这给了我0.125的答案。如何减去这些日期字段并以hh:mm:ss格式结束?

2 个答案:

答案 0 :(得分:1)

假设mopendmopstart都是date列,减去两个日期会返回天数差异。如果你想把它格式化为小时,分钟和秒,你需要做一些数学运算。

with diffs as (
   select 0.125 diff_in_days from dual
)
select trunc( mod(diff_in_days * 24, 24) ) diff_in_hours,
       trunc( mod(diff_in_days * 24 * 60, 60) ) diff_in_mins,
       trunc( mod(diff_in_days * 24 * 60 * 60, 60) ) diff_in_secs
  from diffs;

另一种方法是使用interval并提取单个组件

with diffs as (
   select numtodsinterval( 0.125, 'day' ) diff_interval from dual
)
select extract( hour from diff_interval ) diff_in_hours,
       extract( minute from diff_interval ) diff_in_mins,
       extract( second from diff_interval ) diff_in_secs
  from diffs;

答案 1 :(得分:-3)

你可以尝试

TO_DATE((WXN_MOPACTIVITY.MOPEND - WXN_MOPACTIVITY.MOPSTART), 
         'YYYY-MM-DD HH24:MI:SS') AS TIME_DIF

这应该有效。 (我现在没有任何oracle DB)