Converting time difference to a given format in Oracle

后端 未结 4 1488
情书的邮戳
情书的邮戳 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
    

提交回复
热议问题