Skip to content

Instantly share code, notes, and snippets.

@roberto-filho
Last active July 3, 2018 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roberto-filho/3870f29acc0db42d99cf8114da4116a9 to your computer and use it in GitHub Desktop.
Save roberto-filho/3870f29acc0db42d99cf8114da4116a9 to your computer and use it in GitHub Desktop.
Postgresql function to calculate the months between two dates.
CREATE OR REPLACE FUNCTION months_between(
date,
date)
RETURNS integer AS
$BODY$
DECLARE
dt_final date;
BEGIN
dt_final := $2;
IF $1 = date_trunc('MONTH', $1)::date AND $2 = last_day_of_month($2) THEN
-- É um mês inteiro
dt_final := dt_final + interval '1 day';
END IF;
RETURN abs(months_of(age($1, dt_final)));
END; $BODY$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION months_of(interval)
RETURNS integer AS
$BODY$
SELECT extract(years from $1)::int * 12 + extract(month from $1)::int
$BODY$
LANGUAGE sql;
@vicicode
Copy link

vicicode commented Jul 3, 2018

where is last_day_of_month

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment