phpstrtotime

strtotime() ignores year when date is in "Y, F j" format in php


I have just noticed that if the date string is mentioned in "Y, F j" format then strtotime() function in PHP ignores the year while converting it to the Unix Timestamp and always return timestamp with current year

For example, Lets take 2 dates with same month and date but different years and run them through strtotime function

strtotime('2021, October 8') = 1665260460

strtotime('2014, October 8') = 1665260040

as you can see, the datse above are 7 years apart but their time stamp are same and if you try to convert that timestamp into human date with same "Y, F j" format then it returns 2022, October 8.

I tried searching for plausible explanation but I couldn't find any. Does anyone have any idea about why strtotime() behaves strangely for this particular date format? Also what can be the possible solution to this if I cannot use strtotime()


Solution

  • Deceze has already answered you the reason that strtotime fails to recognize date if in "Y, F j" format. (nothing is perfect, imagine if you are the one to write the strtotime PHP function then you should understand that it cannot recognize everything you throw at it)

    And you asked Also what can be the possible solution to this

    Please use (j F Y) Day Month Year (I mean: 8 October 2021, 8 October 2014 etc.)

    So the code is:

    <?php
    echo(strtotime("8 October 2021") . "\n");
    
    echo(strtotime("8 October 2014") . "\n");
    
    ?>
    

    But if you are having source data like "2021, October 8", just do a simple data parsing to make it "j F Y", then pass to strtotime. (simple, right ?)

    Sandbox: https://onlinephp.io/c/9f8ea