我已经编写了一个程序来查找两个日期之间的差异,并以YYYY-MM-DD
格式显示结果但遇到错误。任何人都可以帮我吗?
CREATE OR REPLACE PROCEDURE DATECALCULATOR(DATE_1 IN DATE, DATE_2 IN DATE) AS
DATEDIFF DATE;
BEGIN
DATEDIFF=TO_DATE(DATE_1,'YYYY-MM-DD')-TO_DATE(DATE_2,'YYYY-MM-DD');
DBMS_OUTPUT.PUT_LINE ('Date difference is: ' || TO_DATE(DATEDIFF,'YYYY-MM-DD'));
END;
/
超出程序代码:
EXECUTE DATECALCULATOR('2017-09-10', '2010-01-01');
答案 0 :(得分:3)
如果从其他日期中减去,则会得到这两个日期之间的天数。您无法通过to_date
函数将此值转换为日期。你希望得到什么日期,例如日期之间的差异456天它的意思是:
1 year 3 month and several days
返回格式化的字符串值可能更好吗?
答案 1 :(得分:2)
使用INTERVAL DAY TO SECOND
类型将格式设为+D HH24:MI:SS.FF6
:
CREATE OR REPLACE PROCEDURE DATECALCULATOR(
DATE_1 IN DATE,
DATE_2 IN DATE
) AS
DATEDIFF INTERVAL DAY(9) TO SECOND;
BEGIN
DATEDIFF= (DATE_1- DATE_2) DAY(9) TO SECOND;
DBMS_OUTPUT.PUT_LINE('Date difference is: ' || DATEDIFF );
END;
/
或者,使用MONTHS_BETWEEN
函数获取YYYY-MM-DD
格式的差异:
CREATE OR REPLACE PROCEDURE DATECALCULATOR(
range_end IN DATE,
range_start IN DATE
) AS
DIFF NUMBER := TRUNC( MONTHS_BETWEEN( DATE_1, DATE_2 ) ) - 1;
dt DATE := ADD_MONTHS( range_start, diff );
d INTEGER := TRUNC( range_end - dt );
dy INTEGER := EXTRACT( DAY FROM LAST_DAY( dt ) );
m INTEGER;
y INTEGER;
BEGIN
IF d > dy THEN
diff := diff + 1;
d := d - dy;
END IF;
m := MOD( TRUNC( diff ), 12 );
y := TRUNC( diff / 12 );
DBMS_OUTPUT.PUT_LINE('Date difference is: '
|| TO_CHAR( y, '0009' ) || '-' || TO_CHAR( m, 'FM09' ) || '-' || TO_CHAR( d, 'FM09' )
);
END;
/