Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first weekday in a month with strtotime

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?

like image 728
Yarin Avatar asked Dec 05 '10 05:12

Yarin


People also ask

Why is Strtotime return false?

strtotime expects a "English textual datetime" (according to the manual), which Y-D-M is not. Any time strtotime returns false, it simply doesn't understand your string, which in this application is expected.

What does Strtotime return?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

How do you get a date from Strtotime?

Code for converting a string to dateTime$date = strtotime ( $input ); echo date ( 'd/M/Y h:i:s' , $date );


1 Answers

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:

$date1 = strtotime("first wednesday of 2010-12");
$date2 = strtotime("first wednesday 2010-12");
$date3 = strtotime("wednesday 2010-12");

5.2 Results:

1969-12-31
2010-12-08
2010-12-01

5.3 Results:

2010-12-01
2010-12-08
2010-12-01

Therefore only the third method returns correct results across PHP 5 versions.

like image 79
Yarin Avatar answered Sep 27 '22 23:09

Yarin