PHP Function – Calculating Days In A Month
All developers keep a tool box of useful functions and classes that they pick up or write along the way and this PHP came to me while I was writing an event calendar page for a customer.
I should mention that PHP does offer a cal_days_in_month function for PHP builds of PHP 4.0.7 and higher, but I prefer using the below function because it is guaranteed to work on all PHP version because it is based solely on logic.
The Code
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);
}
One line of logic provides the number of days in a month, taking into account leap years, and all on one line.
Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices. While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...
It's no secret that Facebook has become a major traffic driver for all types of websites. Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly. And of course there are Facebook "Like" and "Recommend" widgets on every website. One...
CSS filters aren't yet widely supported but they are indeed impressive and a modern need for web imagery. CSS filters allow you to modify the display of images in a variety of ways, one of those ways being displaying images as grayscale.
Doing so requires the...
One of my guilty pleasures is scoping out the latest celebrity gossip from PerezHilton.com, DListed.com, and JoBlo.com. Unfortunately, these sites occasionally post NSFW pictures which makes checking these sites on lunch a huge gamble -- a trip to HR's office could be just a click away.
Since...
Thanks for your very helpful site! Love the tips.
Hi David,
PHP versions 4&5 also offer the
date("t")
function which returns number of days in given month.michael is right:
$totDays = date("t",strtotime($year.'-'.$_month.'-01'));
LOL.. Thanks Michael and Paskuale but I think you’re both missing the point! It’s nice to be told that we can get the days directly but the point about this function is that it’s an easily recognisable way to learn how ternary functions in PHP.
Very useful for noobies such as myself – thanks David :)
LOL.. Thanks Michael and Paskuale but I think you’re both missing the point! It’s nice to be told that we can get the days directly but the point about this function is that it’s an easily recognisable way to learn how ternary functions in PHP.
Very useful for noobies such as myself – thanks David :)