How to calculate Independence Day observances with PHP

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles