Converting time difference to a given format in Oracle

后端 未结 4 1482
情书的邮戳
情书的邮戳 2021-01-17 22:34

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

相关标签:
4条回答
  • 2021-01-17 22:39

    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
    
    0 讨论(0)
  • 2021-01-17 22:42

    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

    0 讨论(0)
  • 2021-01-17 22:50

    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
    )
    /
    
    0 讨论(0)
  • 2021-01-17 23:02
    select 24 * (EVENT_DATE_B - EVENT_DATE_A) || ':' || '00'
    from your_table
    

    SQLFiddle demo

    0 讨论(0)
提交回复
热议问题