PHP strtotime for June returns July

I am stumped why the following PHP strtotime function returns "07" as the month number, not "06" when $ monthToGet = "June":

$monthToGet = $_GET['mon']; $monthAsNumber = date('m', strtotime($monthToGet)); 

From the search, it looks like this could be due to the default date parameters (in this case day and year), since I did not specify them. Will this be the reason?

Any suggestions appreciated!

+8
php
source share
3 answers

TL DR

You're right

 echo date("m", strtotime("June")); -> 07 

However, this works:

 echo date("m", strtotime("1. June 2012")); -> 06 

The problem is due

Today is 31. July 2012 , and since you provide only a month, the current day and current year are used to create a valid date.

See the documentation:

Note

The function expects that a string containing the English date format will be set and will try to analyze this format in the Unix timestamp (the number of seconds since January 1, 1970 00:00:00 UTC) with respect to the timestamp given in the current time, or the current one time if now not available.

Alternatives

You can use date_parse_from_format() or strptime() to achieve what you want with a slightly different approach.

(Thanks to johannes_ and johann__ for entering them)

+5
source share

Fixed:

 $monthToGet = '1 '. $_GET['mon']; 

But I still don't understand why, since "m" is a valid date format

+1
source share

Today is July 31st. Thus, strtotime only with "June" interpreted as 31 June => 1 July .

Actually:

 echo date("Ymd",strtotime("January")); // 2012-01-31 echo date("Ymd",strtotime("February")); // 2012-03-02 

of course ... only today 31 Jul 2012 :) Tomorrow everything will work.

You are lucky because you found this error only today;)

+1
source share

All Articles