Converting time difference to a given format in Oracle

送分小仙女□ 提交于 2019-12-19 17:39:27

问题


How do I convert EVENT_DATE_B - EVENT_DATE_A which is a number of days to string with HH:MM format?


回答1:


If dates are differ only in time part you can use interval day to second. For instance:

SQL> select (to_date('25.12.12 15:37:32', 'DD.MM.YY HH24:MI:SS')
  2        - to_date('25.12.12 12:45:45', 'DD.MM.YY HH24:MI:SS')) day(0) to second(0) as Time
  3    from dual
  4  ;

TIME
-------------
+0 02:51:47

But obviously it will not always be the case. So you could write a long query to calculate different parts of time, but I think I would go with this simple function:

SQL> create or replace function DaysToTime(p_val in number)
  2  return varchar2
  3  is
  4    l_hours    number;
  5    l_minutes  number;
  6    l_seconds  number;
  7  begin
  8    l_Hours := 24 * p_val;
  9    l_minutes := (l_hours - trunc(l_hours)) * 60;
 10    l_seconds := (l_minutes - trunc(l_minutes)) * 60;
 11    return to_char(trunc(l_hours), 'fm09')  ||':'||
 12           to_char(trunc(l_minutes), 'fm09')||':'||
 13           to_char(trunc(l_seconds), 'fm09');
 14  end;
 15  /

Function created

And now the query would be:

SQL> select DaysToTime(to_date('25.12.12 15:37:32', 'DD.MM.YY HH24:MI:SS')
  2        - to_date('25.12.12 12:45:45', 'DD.MM.YY HH24:MI:SS')) as Time
  3    from dual
  4  ;

TIME
----------
02:51:47



回答2:


Another approach (one query can be on different days):

with tt as (
   select numToDsinterval((EVENT_DATE_B - EVENT_DATE_A ), 'DAY') dsint 
     from t)
select (extract(day from dsint)*24)+extract(hour from dsint) || 
       ':' ||extract(minute from dsint)
from tt

Here is a sqlfiddle demo




回答3:


select 24 * (EVENT_DATE_B - EVENT_DATE_A) || ':' || '00'
from your_table

SQLFiddle demo




回答4:


I think you need to find out the number of days between date1 and date2, then subtract this difference from date2 and convert final date to your format. Copy/paste and see the output:

Select date2, days_between, to_char(date2-days_between, 'mm-dd-yyyy hh24:mi:ss') end_date
From
(
Select sysdate date2 
     , trunc(sysdate)-to_date('20-DEC-2012') days_between  --'20-DEC' is start_date
From dual
)
/


来源:https://stackoverflow.com/questions/14030654/converting-time-difference-to-a-given-format-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!