How to Determine/Check if a Year is Leap Year in PHP?

Problem:

You want to check whether a year is leap year.

Solution:

You can use any of the following methods to find out the leap year.

Method 1: Using date() function

The date() function returns the formatted string according to the formatting character used as parameter. We’ll use the formatting character “L” which tells whether a year is leap year or not.

The following example will show if the current year is a leap year-

<?php
$isLeapYear = date("L");
echo ($isLeapYear == 1)? "The current year is a leap year" : "The current year is not a leap year";
?>

[wpdm_file id=131]

Output:
The current year is not a leap year

Method 2: Using strtotime() function

You may want to check whether a specific year is leap year or not. Using strtotime() function to find out whether a year is leap year or not is 2 steps process-

  1. Convert a date of the year, you want to check, to its equivalent timestamp. The timestamp of a date is number of seconds since January 1 1970 00:00:00 UTC.
  2. Then, check whether the year is leap year using date() function with “L” formatting character that we used in the method 1 above.

The following example will show whether 2012 was a leap year-

<?php
$date = "2012-01-01";
$timestamp = strtotime($date);
$isLeapYear = date("L", $timestamp);
echo ($isLeapYear == 1)? "The a specified year was leap year" : "The a specified year was not a leap year";
?>

[wpdm_file id=132]

Output:
The a specified year was leap year

Method 3: Using format() method of DateTime class from SPL

PHP provides some excellent ready-made classes to help developers to solves every day issues (in total it is called SPL – Standard PHP Library). One of those classes is DateTime. Using this class, we’ll find out whether a year is a leap year or not in the following two steps-

  1. Create a DateTime Object from the the date you want check
  2. Use format() method with the formatting character “L” to format the date object and returns the year is leap year or not.

See the following example-

<?php
$date = "2012-01-01";
$dateObj = new DateTime($date);
$isLeapYear = $dateObj->format("L");
echo ($isLeapYear == 1)? "The a specified year was leap year" : "The a specified year was not a leap year";
?>

[wpdm_file id=133]

Output:
The a specified year was leap year