Add a interval to a given date in postgresql


/ Published in: SQL
Save to your folder(s)

Add a given interval to a date. The intervals can be year, month or day


Copy this code and paste it in your HTML
  1. CREATE OR REPLACE FUNCTION dateadd(diffType CHARACTER VARYING(15), incrementValue INT, inputDate TIMESTAMP) RETURNS TIMESTAMP AS $$
  2. DECLARE
  3. YEAR_CONST CHAR(15) := 'year';
  4. MONTH_CONST CHAR(15) := 'month';
  5. DAY_CONST CHAR(15) := 'day';
  6.  
  7. dateTemp DATE;
  8. intervalValue VARCHAR (100);
  9. BEGIN
  10. IF LOWER($1) = LOWER(YEAR_CONST) THEN
  11. dateTemp := inputDate + INTERVAL '$2 year';
  12. ELSEIF LOWER($1) = LOWER(MONTH_CONST) THEN
  13. dateTemp := inputDate + INTERVAL '$2 months';
  14. ELSEIF LOWER($1) = LOWER(DAY_CONST) THEN
  15. dateTemp := inputDate + INTERVAL '$2 day';
  16. END IF;
  17.  
  18. RETURN dateTemp;
  19. END;
  20. $$ LANGUAGE plpgsql;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.