Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strtotime() "first monday february" returns second monday if february 1st is a monday

I'm working on a PHP function which calculates holidays:

function holidays($country = 1, $timespan_start = 0, $timespan_end = 0)

The holidays are returned as timestamps in an array.

Since I have to calculate dates like the first Monday of February, I tried strtotime("first monday february $year") and I've discovered that this does not work for 2010, since 02/01/2010 is a Monday - I get February 8th instead.

This bug is actually mentioned in the change log: In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.

But I'm using PHP 5.3.8. Why am I experiencing this error?

like image 270
basic6 Avatar asked Oct 11 '11 11:10

basic6


2 Answers

Looks like you are just missing an "of":

echo date('Y-m-d', strtotime('first monday of february 2010'));

will give the expected result. See the PHP Manual on Relative dates for the various input formats.

like image 88
Gordon Avatar answered Nov 14 '22 08:11

Gordon


Depending on your version of PHP the 'of' statement may or may not work. As another solution try:

echo date('Y-m-d',strtotime('monday February 2010'));

will return the first monday of February 2010. Works for all days as well.

like image 32
Kent Avatar answered Nov 14 '22 06:11

Kent