/ Published in: SQL
A function which will give the difference between two dates in days, month or years.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
CREATE FUNCTION datediff (diffType CHARACTER VARYING(15), date1 DATE, date2 DATE) RETURNS INTEGER AS $$ DECLARE YEAR_CONST CHARACTER VARYING(15) := 'year'; MONTH_CONST CHARACTER VARYING(15) := 'month'; DAY_CONST CHARACTER VARYING(15) := 'day'; diffInInterval INTERVAL; diffInDoublePrecision DOUBLE PRECISION := 0; diffInInteger INTEGER := 0; dateTemp DATE; BEGIN diffInInterval := age(date2, date1); IF LOWER($1) = LOWER(YEAR_CONST) THEN diffInDoublePrecision := date_part('Year', diffInInterval); ELSEIF LOWER($1) = LOWER(MONTH_CONST) THEN diffInDoublePrecision := (date_part('Year', diffInInterval) * 12) + date_part('Month', diffInInterval); ELSEIF LOWER($1) = LOWER(DAY_CONST) THEN diffInDoublePrecision := endDate - startDate; END IF; diffInInteger := CAST(diffInDoublePrecision AS INTEGER); RETURN diffInInteger; END; $$ LANGUAGE plpgsql;