Search code examples
phpdatedate-format

Using property in PHP function


I am looping trough a JSON file with

foreach ($json->response as $value) {
    echo date_format($value->arrival->scheduled_time, "H:i:s");

But the date_format PHP function doesn't work with $value->arrival->scheduled_time. What am I missing? $value->arrival->scheduled_time contains a date. For example 2020-12-27T19:55:00.000


Solution

  • date_format() expects parameter one to be a DateTime object. You are giving it a string. Assuming that string is in a valid datetime format, you need to ctreate a DateTime object first and then call date_format().

    foreach ($json->response as $value) {
        $datetime = date_create($value->arrival->scheduled_time);
        echo date_format($datetime , "H:i:s");
    

    or in OOP:

    foreach ($json->response as $value) {
        $datetime = new DateTime($value->arrival->scheduled_time);
        echo $datetime->format("H:i:s");