Cursed Leap Years!
I used to think that leap years only happened every four years. In fact, every centennial year that is not evenly divisible by 400 is not a leap year.
I don’t expect to live to 2100, so it shouldn’t matter. But, unfortunately, in programming world, remembering this caveat on the leap year could result in a bug, or worse, world cataclysm like we
I recently landed this bug and had to write a way out of it. Here’s my solution in PHP, JavaScript, and Cappuccino.
1
2
3
4
5
6
7
8
9
10
11 function isLeapYear($aYear) {
if (($aYear % 4) == 0) {
if (($aYear % 100) == 0 && (($aYear % 400) != 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
1
2
3
4
5
6
7
8
9
10
11 function isLeapYear(aYear) {
if ((aYear % 4) == 0) {
if ((aYear % 100) == 0 && ((aYear % 400) != 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
1
2
3
4
5
6
7
8
9
10
11 + (BOOL)isLeapYear:(int)aYear {
if ((aYear % 4) == 0) {
if ((aYear % 100) == 0 && ((aYear % 400) != 0) {
return NO;
} else {
return YES;
}
} else {
return NO;
}
}
Comments
Xr
Aug 10th, 2009, 5:56 am
Why all the conditions ?
return (y % 400 == 0) || ((y % 100 != 0) && (y % 4 == 0));
Adapt according to your language of choice. You can even use a macro in C/C++.
Aug 10th, 2009, 5:58 am
Err, the two equal signs were eaten by the comment parser, but you get the idea :)


Joel Perras
Aug 7th, 2009, 2:44 pm
That’s a bit of overkill for PHP – there’s a built in flag in date() to check if a year is a leap year.
date(‘L’, strtotime(‘whatever date string’));