[英]How to calculating the number of days between two dates assuming every month has 31 days in Oracle
How would you go about calculating the number of days between two dates while 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
Does something like this work for you:这样的事情对你有用吗:
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;
Using @Zakaria's input, I came up with the following solution:使用@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
;
Result:结果:
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.