Get Your Leap Year Calculation Right

Mar 19 2008

In the last article, I discussed the standardization of date formats. On a related note, I found that many people don’t know how to calculate leap years. It is trivial to get it right, but even experienced programmers screw it up. So how to find out whether a year is leap year or not?

Consider the year YYYY. The rules are:

  • If YYYY is divisible by 400, it is a leap year
  • If YYYY is divisible by 100, it is not a leap year
  • If YYYY is divisible by 4, it is a leap year

This can be expressed in C, C++, Javascript or Java code as:

isLeap = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

Some people don’t know about the rule of 100 and 400. Ask your colleagues to know how many of them know these rules; and tell them the rules so that the programs they write will work even after 4, 100 or 400 years. As we know, maintainig legacy software is a big headache for software companies. There is a chance that the software you write may survive 400 years.

3 responses so far

  • Lyman says:

    You may want to correct this. Last time I checked, a statement like:

    year % 4;

    will return 0, 1, 2, or 3. This would mean that 3 out of every 4 years is a leapyear in your code.

    What you probably meant was:

    isLeap = (year % 4 == 0) …

    the ‘% 100′ and ‘% 400′ expressions are incorrect in the same way as well.

    Thanks.

    Lyman

  • WhatWhat says:

    “There is a chance that the software you write may survive 400 years.” …. yeah, that is true…..but wtf would i care? its 400!!!! years later!!!!

  • Niyaz PK says:

    Thanks Lyman. Corrected.

    WhatWhat,
    What we enjoy now in our lifetime are the choices made by people hundreds of years ago.

Leave a Reply