How to tell if it's a leap year with PHPHow to tell if it's a leap year with PHP

Posted April 29th, 2008 in PHP

PHP contains a useful date function which can be used to determine if the current year or a specific year is a leap year. This post looks at how to use the date function to do this.

Brief overview of the PHP date() function

The date function works like this:

date('format string');
or
date('format string', $date);

where 'format string' is the string containing the date format specifiers. The optional $date parameter is a UNIX timestamp representation of the datetime. If it is omitted then the current datetime is used.

An example to show the current date in YYYY-MM-DD format would look like this:

echo date('Y-m-d');

Using date() to work out if it's a leap year

PHP has a number of formatting placeholders for the date() function. One of these is "L" which returns 1 if it's a leap year, and 0 if it is not. For example, this would display 1 running this example code when this post was written, in 2008, because 2008 is a leap year:

echo date('L');

If the current year was 2009 then it would display 0, because 2009 is not a leap year.

The second example below shows a loop looking at the years 2000 to 2010. It outputs the year, and then 'Yes' if it's a leap year or 'No' if it is not.

for($i = 2000; $i < 2011; $i++) {
    echo $i, ': ', (date('L', strtotime("$i-01-01")) ? 'Yes' : 'No'), '<br       />';
}

This would display the following:

2000: Yes
2001: No
2002: No
2003: No
2004: Yes
2005: No
2006: No
2007: No
2008: Yes
2009: No
2010: No

Just a quick explanation about some of the bits of the code...

date('L', strtotime("$i-01-01"))

The above part will substitute the numbers 2000 to 2010 for the $i variable, thus making values 2000-01-01 to 2010-01-01. The strtotime() function converts this representation of the date into a UNIX timestamp (more information about this here in my Using strtotime with PHP article). And the 'L' format tells date() to tell us whether or not it's a leap year.

((...) ? 'Yes' : 'No')

If the date() function returns true then it will return the first value after ?. If it returns false it will return the value after the :. 1 will return true, and 0 false, so we will echo out 'Yes' or 'No' instead of 1 or 0 which is much more human readable.

Summary

You can the PHP date() function to work out if the current year, or a specific year, is a leap year or not. This is illustrated in the examples in this post.

Related posts:

Comments

blog comments powered by Disqus