Tuesday 15 July 2008

Oracle date function to add or subtract days, years, months, minutes, hours or seconds

Hi

I recently created this function to calculate the date result when adding or subtracting two dates in oracle. May be useful to others so here it is:

CREATE OR REPLACE Function FOCUSTEST.DateADD(
v_datePart  VARCHAR2
, v_value     NUMBER
, v_date      TIMESTAMP)
RETURN TIMESTAMP
AS
v_result    TIMESTAMP;
BEGIN

IF (UPPER(v_datePart) = 'YY') THEN
v_result := ADD_MONTHS(v_date, (v_value * 12));
END IF;
IF (UPPER(v_datePart) = 'MM') THEN
v_result := ADD_MONTHS(v_date, v_value);
END IF;
IF (UPPER(v_datePart) = 'DD') THEN
v_result := v_date + v_value;
END IF;
IF (UPPER(v_datePart) = 'HH') THEN
v_result := v_date + (v_value / 24);
END IF;
IF (UPPER(v_datePart) = 'MI') THEN
v_result := v_date + (v_value / (24 * 60));
END IF;
IF (UPPER(v_datePart) = 'SS') THEN
v_result := v_date + (v_value / (24 * 60 * 60));
END IF;

DBMS_OUTPUT.PUT_LINE(v_result);
RETURN v_result;

END;