We Recommend

SQL Cookbook SQL Cookbook
Written in O'Reilly's popular Problem/Solution/Discussion style, the SQL Cookbook is sure to please. Anthony's credo is: "When it comes down to it, we all go to work, we all have bills to pay, and we all want to go home at a reasonable time and enjoy what's still available of our days." The SQL Cookbook moves quickly from problem to solution, saving you time each step of the way.


Posted By

arunpjohny on 10/16/07


Tagged

postgres


Versions (?)


Difference between two dates in Postgresql


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

  1. CREATE OR REPLACE FUNCTION datediff (diffType Character Varying(15), date1 Date, date2 Date) RETURNS integer AS $$
  2. DECLARE
  3. YEAR_CONST Character Varying(15) := 'year';
  4. MONTH_CONST Character Varying(15) := 'month';
  5. DAY_CONST Character Varying(15) := 'day';
  6.  
  7. diffInInterval Interval;
  8. diffInDoublePrecision Double Precision := 0;
  9. diffInInteger Integer := 0;
  10. dateTemp Date;
  11. BEGIN
  12.  
  13. diffInInterval := age(date2, date1);
  14.  
  15. IF lower($1) = lower(YEAR_CONST) THEN
  16. diffInDoublePrecision := date_part('Year', diffInInterval);
  17. ELSEIF lower($1) = lower(MONTH_CONST) THEN
  18. diffInDoublePrecision := (date_part('Year', diffInInterval) * 12) + date_part('Month', diffInInterval);
  19. ELSEIF lower($1) = lower(DAY_CONST) THEN
  20. diffInDoublePrecision := endDate - startDate;
  21. END IF;
  22.  
  23. diffInInteger := CAST(diffInDoublePrecision AS Integer);
  24. RETURN diffInInteger;
  25. END;
  26. $$ LANGUAGE plpgsql;

Report this snippet 

You need to login to post a comment.