Search code examples
phpdatetime

My code is somehow changing the date and in need to stop it


I'm having a problem with dates. I have this code

        echo "<br>2a. Recall action date: ".$recallActionDate."<br>";
        $recallActionDate = date("Y-m-d H:i:s", strtotime($recallActionDate));
        echo "<br>2b. Recall action date: ".$recallActionDate."<br>";

this is a printout of the result:

2a. Recall action date: 26/06/2019

2b. Recall action date: 1970-01-01 00:00:00

I can't figure out how the date is getting changed - any ideas please?


I added the following code:

 echo "<br>2a. Recall action date: ".$recallActionDate."<br>";
            echo " string to time ".strtotime($recallActionDate)."<br>";
            echo "a is " . is_string($recallActionDate) . "<br>";
            $recallActionDate = date("Y-m-d H:i:s", strtotime($recallActionDate));
            echo "<br>2b. Recall action date: ".$recallActionDate."<br>";

to allow me to error check and the result is

2a. Recall action date: 26/06/2019 string to time a is 1

2b. Recall action date: 1970-01-01 00:00:00

Recall action date: 1970-01-01 00:00:00


Solution

  • We can infer that at least casting $recallActionDate to a string gives "26/06/2019"; and strtotime requires a string. So the problem with this code:

    $recallActionDate = "26/06/2019";
    $recallActionDate = date("Y-m-d H:i:s", strtotime($recallActionDate));
    

    Is that strtotime deals with dates in the American mm/dd/yyyy format and not dd/mm/yyyy.

    You have 2 options:

    Option 1 - Change how you are fetching the date from MySQL

    You mentioned in a comment that you are getting the date "26/06/2019" from MySQL. If this is stored as a date in MySQL it would be far preferable to fetch it from the database in the YYYY-MM-DD format, which strtotime will parse correctly (as well as being an unambiguous international date format (ISO 8601) used consistently across computing!)

    Option 2 - Tell PHP how the date is formatted

    $recallActionDate = "26/06/2019";
    $recallActionDate = DateTime::createFromFormat('d/m/Y', 
    $recallActionDate);
    echo $recallActionDate->format("Y-m-d");
    

    Using the createFromFormat function of PHPs DateTime you can specify how the string is formatted, and create a date object from that. Then you can use the format method of that DateTime object to output the date in the format that you'd like.