Last active
July 3, 2018 15:27
-
-
Save roberto-filho/3870f29acc0db42d99cf8114da4116a9 to your computer and use it in GitHub Desktop.
Postgresql function to calculate the months between two dates.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where is last_day_of_month