PHP strtotime for June returns July

前端 未结 3 2071
予麋鹿
予麋鹿 2021-01-17 23:09

I\'m stumped as to why the following PHP strtotime function returns \'07\' as the month number, rather than \'06\' when $monthToGet = \'June\':

$monthToGet =         


        
相关标签:
3条回答
  • 2021-01-17 23:39

    Today is 31 Jul. So a strtotime with only "June" is interpreted as 31 June => 1 July.

    In fact:

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

    of course... only today 31 Jul 2012 :) Tomorrow all will works.

    You're lucky because you found this bug just today ;)

    0 讨论(0)
  • 2021-01-17 23:43

    TL;DR

    You are right

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

    However, this does work:

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

    The problem explained

    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 to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

    Alternatives

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

    (Thanks to johannes_ and johann__ for their input)

    0 讨论(0)
  • 2021-01-17 23:43

    Fixed with :

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

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

    0 讨论(0)
提交回复
热议问题