Skip to content

Instantly share code, notes, and snippets.

@benmacleod
Created February 14, 2012 05:00
Show Gist options
  • Save benmacleod/1823672 to your computer and use it in GitHub Desktop.
Save benmacleod/1823672 to your computer and use it in GitHub Desktop.
Leap year agnostic day of year function for Postgres PL/SQL
CREATE OR REPLACE FUNCTION yday(time_in TIMESTAMP) RETURNS INTEGER AS $$
DECLARE
yr INTEGER;
mnth INTEGER;
yday INTEGER;
BEGIN
-- Ensure March 1st and after always have the same day of year across leap-years
-- by adding 1 to the day of year for months after Feb in non-leap years
yday := EXTRACT(doy FROM time_in);
yr := EXTRACT(year FROM time_in);
mnth := EXTRACT(month FROM time_in);
IF yr % 4 > 0 and mnth > 2 THEN
yday := yday + 1;
END IF;
RETURN yday;
END;
$$ LANGUAGE plpgsql;
@yevhene
Copy link

yevhene commented Jan 7, 2021

This function not includes adjustments introduced by Gregorian calendar.

Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 are not leap years, but the years 1600 and 2000 are.

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