prev up next   top/contents search

comp.lang.c FAQ list · Question 20.32

Q: Is (year % 4 == 0) an accurate test for leap years? (Was 2000 a leap year?)


A: No, it's not accurate (and yes, 2000 was a leap year). The actual rules for the present Gregorian calendar are that leap years occur every four years, but not every 100 years, except that they do occur every 400 years, after all. In C, these rules can be expressed as:

	year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
See a good astronomical almanac or other reference [footnote] for details.

Actually, if the domain of interest is limited (perhaps by the range of a signed 32-bit time_t) such that the only century year it encompasses is 2000, the expression

	year % 4 == 0		/* 1901-2099 only */
is accurate, if less than robust.

If you trust the implementor of the C library, you can use mktime to determine whether a given year is a leap year; see the code fragments in questions 13.14 or 20.31 for hints.

Note also that the transition from the Julian to the Gregorian calendar involved deleting several days to make up for accumulated errors. (The transition was first made in Catholic countries under Pope Gregory XIII in October, 1582, and involved deleting 10 days. In the British Empire, eleven days were deleted when the Gregorian calendar was adopted in September 1752. A few countries didn't switch until the 20th century.) Calendar code which has to work for historical dates must therefore be especially careful.

See also question 13.14b.


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North