can i keep a day of the month in time?

Perhaps this function can make you happy:

CREATE OR REPLACE FUNCTION add_months_preserve_end(d date, i interval)
   RETURNS date
   LANGUAGE sql IMMUTABLE STRICT AS
$$SELECT
   CASE WHEN date_trunc('month', d) + INTERVAL '1 month' = d + INTERVAL '1 day'
             AND i = date_trunc('month', i)
        THEN (date_trunc('month', d) + i + INTERVAL '1 month -1 day')::date
        ELSE (d + i)::date
   END$$;

It treats days at the end of the month differently.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top