PHP strtotime() “first monday february” returns se

2019-02-22 07:24发布

问题:

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?

回答1:

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.



回答2:

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.