I'm trying to figure out the first wednesday of a given month using strtotime
, but the "first wednesday" argument fails whenever the first wednesday happens to fall on the 1st.
For a more general illustration of this problem, see the following code and result:
$mon = strtotime("December 2010 first monday");
$tue = strtotime("December 2010 first tuesday");
$wed = strtotime("December 2010 first wednesday");
$thu = strtotime("December 2010 first thursday");
$fri = strtotime("December 2010 first friday");
$sat = strtotime("December 2010 first saturday");
$sun = strtotime("December 2010 first sunday");
echo strftime("%m/%d/%y", $mon) . "<br>";
echo strftime("%m/%d/%y", $tue) . "<br>";
echo strftime("%m/%d/%y", $wed) . "<br>";
echo strftime("%m/%d/%y", $thu) . "<br>";
echo strftime("%m/%d/%y", $fri) . "<br>";
echo strftime("%m/%d/%y", $sat) . "<br>";
echo strftime("%m/%d/%y", $sun) . "<br>";
Results in:
12/06/10
12/07/10
12/08/10
12/02/10
12/03/10
12/04/10
12/05/10
Notice something? Shouldn't one day of the week coincide with the 1st of the month? But it never does, and instead the second instance of the day, on the 8th, is always returned.
Anyone have an explanation for this?
Building off the answers provided, one needs to be aware of differences in relative date formatting between php 5.2 and php 5.3.
TEST:
5.2 Results:
5.3 Results:
Therefore only the third method returns correct results across PHP 5 versions.
I found this note in the PHP manual.
"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."
PHP 5.5.11
$firstWeekdayOfMonth = new DateTime('first weekday 0 jun 2016');
I don't know why, but the zero kind of force the strtotime parser to start at the beginning of the month considering the first day.
I believe it's the order in which you are placing values. When you write "December 2010", it already is going to 12/01/2010. When adding "first {day}", function goes for that very first day, after the 12/01/2010. I think if you declare the "first {day}" value and then "december 2010" it should work fine.
I don't have any explanation as I'm also dazzled, but I managed to find out how you get the correct date by omitting the "first", like so:
It's just your formatting that is incorrect. You need to include
of
:Prints:
The accepted solution works, but you would encounter problems if you wanted to find the second weekday:
Prints:
There are some examples given in the docs:
http://www.php.net/manual/en/datetime.formats.relative.php
The second block of notes in the above documentation explains how
of
affects the date calculation process: