David Golding



Cursed Leap Years!

By David Golding | Print This Post Print This Post

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 saw didn’t see with Y2K.

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

3 Responses to “Cursed Leap Years!”

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’));

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++.

Xr

Aug 10th, 2009, 5:58 am

Err, the two equal signs were eaten by the comment parser, but you get the idea :)



Submit Comment


Beginning CakePHP: From Novice to Professional by David Golding

David Golding

A blog about CakePHP, web design, and grad studies in religion. © 2008, D. Golding