Skip to content

Instantly share code, notes, and snippets.

@ianthrive
Created June 27, 2017 04:36
Show Gist options
  • Save ianthrive/e62d964d299cfcf12f23b5c588b8b302 to your computer and use it in GitHub Desktop.
Save ianthrive/e62d964d299cfcf12f23b5c588b8b302 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION first_dow_of_month(year INTEGER, month INTEGER, dow INTEGER)
RETURNS date LANGUAGE plpgsql
AS $$
DECLARE
first_day DATE := (year||'-'||month||'-1')::DATE;
first_day_plus_week DATE := first_day + '1 week'::INTERVAL;
BEGIN
RETURN first_day_plus_week + dow - DATE_PART('dow', first_day_plus_week)::INTEGER;
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment