簡體   English   中英

假設每個月在 Oracle 中有 31 天,如何計算兩個日期之間的天數

[英]How to calculating the number of days between two dates assuming every month has 31 days in Oracle

go 假設每個月在 Oracle 中有 31 天,您將如何計算兩個日期之間的天數?

select to_date('20210201','YYYYMMDD') - to_date('20210128','YYYYMMDD') from dual; --result 4
select to_date('20210301','YYYYMMDD') - to_date('20210228','YYYYMMDD') from dual; --result 1, expected 4

這樣的事情對你有用嗎:

select 
(extract(year from date '2021-03-01') - extract(year from date '2021-02-28')) * 31 * 12
+ (extract(month from date '2021-03-01') - extract(month from date '2021-02-28')) * 31
+ (extract(day from date '2021-03-01') - extract(day from date '2021-02-28'))
as diff
from dual;

小提琴

使用@Zakaria 的輸入,我想出了以下解決方案:

create or replace FUNCTION DAYS_BETWEEN_DATES_31
    (in_from IN DATE
    ,in_to   IN DATE
    )
RETURN NUMBER
IS
    v_result NUMBER := 0;
    v_compensation NUMBER := 0;
BEGIN
    /*
    This function returns the number of days in a data range assuming every month has 31 days
    */
 
    --calculate the number of days in between the two dates assuming every month has 31 days
    v_result :=
    (extract(year from  in_to) - extract(year from in_from)) * 31 * 12
    + (extract(month from  in_to) - extract(month from in_from)) * 31
    + (extract(day from in_to) - extract(day from in_from))
    + 1;
 
    --if the in_to date is the last day of the month and less than 31, we should compensate for it
    IF extract(day from last_day(in_to)) = extract(day from in_to)
    AND extract(day from in_to) < 31
    THEN
        v_compensation := 31 - extract(day from in_to);
        v_result := v_result + v_compensation;
    END IF;
 
    DBMS_OUTPUT.PUT_LINE('from:'|| to_char(in_from,'DD/MM/YYYY') || ' to:'|| to_char(in_to,'DD/MM/YYYY') || ' + ' || v_compensation || ' : ' ||v_result);
    RETURN v_result;
END
;

結果:

from:01/12/2021 to:30/12/2021    : 30
from:01/12/2021 to:31/12/2021    : 31
from:01/12/2021 to:31/01/2022    : 62
from:01/12/2021 to:28/02/2022 +3 : 93
from:05/01/2022 to:04/02/2022    : 31
from:05/01/2022 to:04/03/2022    : 62
from:05/08/2022 to:30/09/2022 +1 : 58
from:05/08/2022 to:04/10/2022    : 62
from:05/08/2022 to:04/11/2022    : 93
from:25/08/2022 to:30/11/2022 +1 : 100
from:25/11/2022 to:30/11/2022 +1 : 7
from:05/08/2022 to:04/12/2022    : 124
from:05/08/2022 to:31/12/2022    : 151
from:01/01/2022 to:31/12/2022    : 372

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM