How to calculate Independence Day observances with PHP

On this 238th anniversary of the United States of America, I felt it appropriate to post an article on how to determine what day the July 4th National Holiday is observed on. There are two rules to the observances. First, if the holiday falls on a Saturday, it is observed on the Friday before. If it falls on a Sunday, it is observed on the following Monday. The following logic can be applied to many national holidays that follow the same roles of observance:

$date = '2014-07-04'
$day  = date('w', $date // Using 'w' instead of 'N' to be < 5.1 compatible

// Falls on a Saturday
if ($day == 6)
{
	$holiday = date('Y-m-d', strtotime($date . ' -1 day'
}
// Falls on a Sunday
elseif ($day == 0)
{
	$holiday = date('Y-m-d', strtotime($date . ' +1 day'
}
// Falls any other day
else
{
	$holiday = $date
}

It’s in the comments already, but the reason for using the slightly more confusing “w” format, which starts at 0 instead of 1, is to ensure the code will work on PHP versions prior to 5.1 which is when the “N” format was introduced.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.