Simplify your business
Friday, 29 August 2008 9:21 am

PHP leap year calculation

Saturday, 24 March 2007  

A simple little function to calculate whether a specified year is a leap year or not:

function isleapyear($year = '') {
   if (empty($year)) {
      $year = date('Y');
   }
   $year = (int) $year;
   if ($year % 4 == 0) {
      if ($year % 100 == 0) {
         return ($year % 400 == 0);
      } else {
         return true;
      }
   } else {
      return false;
   }
}

The algorithm applied above, translated to everyday language, is something like this:

If the year is divisible by 100, then it’s not, unless the year is divisible by 400, when it is. Otherwise, if the year is divisible by 4, then it is. Otherwise, it’s not.

Did you get all that? I know, it’s probably easier to understand by looking at the code.

Posted in PHP, Programming, Tips by Ivan
Blinklist icon Del.iocio.us icon Furl icon Reddit icon Technorati icon Yahoo! icon

Got something to say?

To protect your privacy, your email address will not be displayed.





Some basic rules for commenting:

  • Watch your language.
  • Keep comments on-topic and relevant.
  • You can use basic XHTML tags for formatting and linking but not bbcode.
  • Comments are moderated, so don't double post if your comment doesn't appear immediately.
  • Please proof-read your comments for spelling and grammar mistakes.
  • Watch your language.