Oracle : how to subtract two dates and get minutes of the result

后端 未结 4 403
粉色の甜心
粉色の甜心 2021-01-04 01:34

I wrote this function to get minutes from a date, but I cannot get minutes between two dates, How to get that ?

FUNCTION get_minute(p_date DATE)
RETURN NUMB         


        
相关标签:
4条回答
  • 2021-01-04 01:53

    I think you can adapt the function to substract the two timestamps:

    return  EXTRACT(MINUTE FROM 
      TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
    -
      TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
    );
    

    I think you could simplify it by just using CAST(p_date as TIMESTAMP).

    return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));
    

    Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

    0 讨论(0)
  • 2021-01-04 01:58

    For those who want to substrat two timestamps (instead of dates), there is a similar solution:

    SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 1440 AS minutesInBetween
    FROM ...
    

    or

    SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 86400 AS secondsInBetween
    FROM ...
    
    0 讨论(0)
  • 2021-01-04 01:58

    I can handle this way:

    select to_number(to_char(sysdate,'MI')) - to_number(to_char(*YOUR_DATA_VALUE*,'MI')),max(exp_time)  from ...
    

    Or if you want to the hour just change the MI;

    select to_number(to_char(sysdate,'HH24')) - to_number(to_char(*YOUR_DATA_VALUE*,'HH24')),max(exp_time)  from ...
    

    the others don't work for me. Good luck.

    0 讨论(0)
  • 2021-01-04 02:02

    When you subtract two dates in Oracle, you get the number of days between the two values. So you just have to multiply to get the result in minutes instead:

    SELECT (date2 - date1) * 24 * 60 AS minutesBetween
    FROM ...
    
    0 讨论(0)
提交回复
热议问题