solvit.io

Get the number of days in a given month using PHP

PHP 5.4 and higher
$numDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);
// $month = 1..12 (1 = January, ..., 12 = December)
Example
$numDays = cal_days_in_month(CAL_GREGORIAN, 2, 2017);
// February 2017 -> $numDays = 28

$numDays = cal_days_in_month(CAL_GREGORIAN, 2, 2020);
// February 2020 -> $numDays = 29
PHP 5.3 and lower
function getMonthDays($month, $year)
{
    return $month == 2
        ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29)))
        : (($month - 1) % 7 % 2 ? 30 : 31)
    ;
}
Example
$numDays = getMonthDays(2, 2017);
// February 2017 -> $numDays = 28

$numDays = getMonthDays(2, 2020);
// February 2020 -> $numDays = 29
Find more solutions about: , , ,