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:
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:
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:
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.
This would display the following:
Just a quick explanation about some of the bits of the code...
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.
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.
0 comments:
Post a Comment