/ Published in: SQL
Getting the difference between two dates in Postgresql. The difference can be in days, months or years.
For difference in days, months or years pass day, month or year as the first argument
For difference in days, months or years pass day, month or year as the first argument
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
CREATE OR REPLACE 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;