I need to calculate the end date of a job based on a start date and a duration (an integer representing the number of working days).
I already wrote a function, based on this answer, that computes the number of weekend days between two dates (start and virtual end).
-- 0 Sunday
-- 1 Monday
-- 2 Tuesday
-- 3 Wednesday
-- 4 Thursday
-- 5 Friday
-- 6 Saturday
CREATE OR REPLACE FUNCTION weekend_days(date, date) RETURNS INT AS
$$
SELECT COUNT(days)::INT
FROM generate_series($1, $2, '1 day') AS days
WHERE EXTRACT(DOW FROM days) BETWEEN 1 AND 5;
$$
LANGUAGE 'sql' IMMUTABLE STRICT;
I want to create a trigger ON INSERT or ON UPDATE that will populate the corresponding end_date
column.
Obviously, adding the weekend days to the given duration does not solve the problem.
Recursion
Is there any way to make a recursive function to continue adding the weekends or holidays?
EDIT: Maybe another good example could be found in this answer, that mixes weekend and holidays.