Get number of days in month with PHP

Problem: get number of days in certain month with PHP, if $m – is a month and $y – is an year.

First solution, hacker-style (source):

(31 - (($m 1) % 2) - ((($m == 2) << !!($y 4)))) ?>

This solution doesn’t work properly for years divisible by 100, and non-divisible by 400 (years 1900 and 2100 are not leap)

Second solution, canonical:

date("t",mktime(0,0,0,$m,1,$y));

This solution works only for dates which can be presented as unix timestamps, therefore it’s not good (depends on PHP version and OS.)

Third solution, proper:

function days_in_month($y,$m)
{//by val petruchek http://petruchek.com
    
$d 31;
    while(!
checkdate($m,$d,$y)) $d--;
    return 
$d;
}

This solution is based on built-in PHP function checkdate() which validates Gregorian date without unix timestamps.

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.