PHP strtotime returning wrong results

后端 未结 3 1495
再見小時候
再見小時候 2020-12-22 12:28

strtotime(\'3rd January,2010\') returns 1230993600 in GMT+5:30.

While according to this, unix timestamp 1230993600 is 3rd January,2009. So it\'s off

相关标签:
3条回答
  • 2020-12-22 12:59

    When you have a comma after the month, it assumes that 2010 is military time instead of the year. If you want it to interpret 2010 as the year, omit the comma.

    0 讨论(0)
  • 2020-12-22 13:04

    The problem is the , in the date string. It seems to separate date from time elements in your string, as

    echo date('Y-m-d H:i:s', strtotime('3rd January, 2010'));
    

    returns

    2009-01-03 20:10:00
    

    whereas

    echo date('Y-m-d H:i:s', strtotime('3rd January 2010'));
    

    (, removed) returns the correct date:

    2010-01-03 00:00:00
    
    0 讨论(0)
  • 2020-12-22 13:11

    strtotime() is not infallible. It is a contextual parser that tries to convert English descriptions of a date into a timestamp. The format you are using appears to be unsuitable for proper parsing.

    You can see the differences in the following examples:

    echo strtotime('3rd January,2010')."<BR>";
    echo strtotime('3 January, 2010')."<BR>";
    echo strtotime('January 3rd, 2010')."<BR>";
    echo strtotime('January 3, 2010')."<BR>";
    

    results in:

    1231042200
    1231042200
    1262505600
    1262505600
    

    The first two return a different timestamp than the last two. Of the formats, the last two are more semantically (English-wise) correct, and I would try to use them instead.

    EDIT

    As other posters have noted, the comma confuses the parser about the date portion due to the order of your date tokens.

    echo strtotime('3rd January 2010')."<BR>";
    

    returns the correct timestamp for your format.

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