How do I know if the current year is a leap year in PHP?
How do I know if the current year is a leap year in PHP?
Another way is to use the date
function with the L
parameter that returns 1
is in leap year, 0
otherwise.
Example for current year:
echo date('L');
For a specific year:
$ano = 2007;
$bissexto= date('L', mktime(0, 0, 0, 1, 1, $ano));
echo $ano . ' ' . ($bissexto? 'é' : 'não é') . ' um ano bissexto.';
See working at ideone .
Another way to know if the year is leap is to know the amount of days in February, this can be done with the argument t
of the function date()
echo date('t', strtotime('2016-02-01')); //29
One workaround is to use a native PHP function that is suitable for this, cal_days_in_month
Examples:
<?php
//2015 não é bisexto
$result = cal_days_in_month(CAL_GREGORIAN, 2, 2015) === 29;
var_dump($result);
//2016 é bisexto
$result = cal_days_in_month(CAL_GREGORIAN, 2, 2016) === 29;
var_dump($result);
Example online: link
A simple function:
function isLeapYear($year = NULL) {
$year = is_numeric($year) ? $year : date('Y');
return cal_days_in_month(CAL_GREGORIAN, 2, $year) === 29;
}
Using:
var_dump(isLeapYear());//Ano atual
var_dump(isLeapYear(2015));//Ano 2015
var_dump(isLeapYear(2016));//Ano 2016
var_dump(isLeapYear(2017));//Ano 2017
Online: link
To do such an operation you can use two ways, but the two lead to the same method: Verify that February ends with the 29th.
Strtotime and date
(date('d', strtotime('last day of february this year')) === '29')
DateTime Object
(new DateTime('last day of february this year'))->format('d') === '29')
This solution is so simple, that some people questioned me in the chat if I was joking. To be convincing, I made an example in IDEONE:
You can use this syntax for any year. If you want to check another year, you could change the excerpt this year
to 2018
or next year
for example.