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

2

7

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?

Builtup answered 11/10, 2011 at 11:0 Comment(1)
I've never trusted strtotime(). :-/Forging
S
17

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.

Stallard answered 11/10, 2011 at 11:20 Comment(3)
That's it, thanks! In the meantime I wrote a little function which calculates the first weekday of a specified month. I could post it if anyone's interested...Builtup
+1 for a working answer. But it's a bit of a horror story if you're expecting strtotime() to cope correctly with arbitrary user input (which is what strtotime() is really aimed at doing). You can't control whether your user will enter the 'of' in their sentence.Forging
@Forging its not meant to work with arbitrary user input at all.Stallard
C
3

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.

Cung answered 6/3, 2015 at 22:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.