How to calculate Thanksgiving’s date with PHP


2 min read
development
php

The topic of this post ended up turning into quite the programming exercise for me. In true PHP fashion, I was able to come up with 3 distinct methods to determine what date Thanksgiving falls on (and have another in mind but it’s just a crappier version of what I’m already doing).

For those unaware, Thanksgiving falls on the fourth Thursday of November (not the last Thursday as some months have five Thursdays). Additionally, Thanksgiving falls between the 22nd and the 28th of the month. There are some exceptions to these rules, specifically in 1940 and 1941 when Thanksgiving was held on the third Thursday.

The Brute Force Solution

It’s the slowest of all of the solutions (about 400% slower), but it does work. We loop backwards through the days and check if it’s a Thursday or not:

for ($i = 28; $i >= 22; $i--)
{
	$thanksgiving = '2013-11-' . $i;

	if (date('N', strtotime($thanksgiving)) == 4)
	{
		break;
	}
}

The Fastest Solution

It’s also the longest solution, we count backwards from the 28th of November and determine an offset in days:

$date = '2013-11-28';
$day  = date('N', strtotime($date));

if ($day < 4)
{
	$thanksgiving = '2013-11-' . (28 - ($day + 3));
}
elseif ($day > 4)
{
	$thanksgiving = '2013-11-' . (28 - ($day - 4));
}
else
{
	$thanksgiving = $date;
}

The One Line Solution

The ace in the hole in any language debate is the ability to pull it off in a single line. This solution is just that, but it’s a tad bit slower than the previous solution.

$thanksgiving = date('Y-m-d', strtotime('fourth thursday of november 2013'));

Conclusion

In this situation, I’d probably just go with the one liner since it was only a tad bit slower than the fastest solution I came up with. I think it’s well worth the trade off and the fact is you probably wouldn’t be doing a ton of calls to determine when Thanksgiving is and if so, just calculate it out by year and keep a copy of disk.

Regardless of the solution you favor, I hope you have a very happy Thanksgiving this year!