Search code examples
phpdatedatetimevar-dump

Error with dateTime when I remove var_dump


I get a date via json in the format dd/mm/yyyy but to save in the mysql database it needs to be in yyyy/mm/dd so I have to convert it:

var_dump($json);

public 'data' => string '27/08/2018' (length=10)

When I run this code snippet:

if(isset($json->data) && $json->data !== '' && !is_null($json->data))
{
    $dt = DateTime::createFromFormat('d/m/Y', $json->data);
    var_dump($dt);
    $parts = explode(' ', $dt->date);
    if(count($parts)>=1)
        $this->Objeto->data = $parts[0];

    var_dump($this->Objeto->data);
}

My var_dump is '2018-08-27' (length=10) and this is the expected result. But when I remove the var_dump($dt) it is returning the following error:

Notice: Undefined property: DateTime::$date in C:\wamp64\www\learning\controller\ControllerNotification.php

Why does this happen when I remove var_dump? How do I solve this problem?

Result when var_dump($dt); is run:

 object(DateTime)[8]
      public 'date' => string '2018-08-27 12:55:44.000000' (length=26)
      public 'timezone_type' => int 3
      public 'timezone' => string 'America/Sao_Paulo' (length=17)

Solution

  • You need to format() it instead:

    if(isset($json->data) && $json->data !== '' && !is_null($json->data)) {
        $dt = DateTime::createFromFormat('d/m/Y', $json->data);
        $this->Objeto->data = $dt->format('Y/m/d h:i:s');
    }