Wow, stumbled across this extremely clever, one line of PHP code to return the correct number of days for any given month, courtesy of the extremely talented David Walsh.
Now while PHP does have an inbuilt function to handle this query (cal_days_in_month), it isn’t always the most ideal of saviors when you consider that it is only valid for PHP 4.0.7 and above installations. David’s on the other hand simply makes use of good old logic and thus pretty much roles out to just about any version of PHP.
And the function? Well, it’s a simple enough call that requires only the target month and year as inputs and looks like this:
function get_days_in_month($month, $year)
{
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month – 1) % 7 % 2 ? 30 : 31);
}
Very clever Mr. Walsh.
You might also enjoy:
-
How to calculate the number of working days in a month, in other words discount Saturdays and Sundays from a month's total number of days. It sounds pre ...
-
Picked this cool little PHP function to calculate and return the last day of a month for any year off the always informative lutrov interactive website the ...
-
Seeing as I'm currently so busy implementing datepickers and such at work at the moment, here's a nifty little bit jQuery/Javascript code that I whipped up ...
-
A big headache for developers, particularly when it comes to database-driven applications, is the differing date formats across country borders, a classic e ...
-
So the latest codename for next year's first planned Ubuntu release has been revealed as being Natty Narwhal, not perhaps the most awe-inspiring of codename ...