Home » Php » "Call to a member function format() on a non-object" when converting date in PHP

"Call to a member function format() on a non-object" when converting date in PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I can not get rid of this error message:

Call to a member function format() on a non-object

So, I go on googling and get some good source like this StackOverflow question.

I tried to do something similar, but I failed. This is my code :

$temp = new DateTime();
/*ERROR HERE*/ $data_umat['tanggal_lahir'] = $data_umat['tanggal_lahir']->format('Y-m-d');
$data_umat['tanggal_lahir'] = $temp;

So, i did trial & errors, and I found out if I do this:

$data_umat['tanggal_lahir'] = date("Y-m-d H:i:s");

The date will successfully converted, BUT it always return today’s date (which i dont want).

I want to convert the date so that 10/22/2013 will be 2013-10-22.

How to&Answers:

You are calling method format() on non-object. Try this:

$data_umat['tanggal_lahir'] = new DateTime('10/22/2013');
$data_umat['tanggal_lahir'] = $data_umat['tanggal_lahir']->format('Y-m-d');

or one-liner:

$data_umat['tanggal_lahir'] = date_create('10/22/2013')->format('Y-m-d');

Answer:

You can use strtotime() to convert this. Its converts the given date to a timestamp and then by using date() function you can convert the timestamp to desired date format.

Try this..

$date = '10/22/2013';
$timestamp = strtotime($date);
$new_date = date('Y-m-d',$timestamp );

Answer:

$data_umat['tanggal_lahir'] is not an instanceof of object DateTime

use to make it instance of DateTime

$data_umat['tanggal_lahir'] = new DateTime();

Answer:

$data_umat['tanggal_lahir'] is not an instance of DateTime, however $temp is.

Is $data_umat['tanggal_lahir'] meant to be be an instance of DateTime

Answer:

$temp = new \DateTime(); (need \ )
/*ERROR HERE*/ $data_umat['tanggal_lahir'] = $data_umat['tanggal_lahir']->format('Y-m-d');
$data_umat['tanggal_lahir'] = $temp;

Answer:

when using Symfony or Slim with Doctrine, try this:

//form[birthday = “2000-12-08”] […]

$birthday = \DateTime::createFromFormat("Y-m-d",$formData['birthday']);

$obejct = new $object();
$object->setBirthday($birthday);
[…]

Answer:

If you encounter this issue when using Symfony, try this hack:

Open:Your Symfony Root/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php

Go to line 50 something where the function convertToDatabaseValue() is declared.

The original code:

return ($value !== null)
        ? $value->format($platform->getDateTimeFormatString()) : null;

Change to:

 return ($value !== null)
            ? $value : null;

Seems Symfony is doing an extra conversion when passing a string as the datestring.

Directly passing a DateTime ojbect won’t work as it will prompt another error saying “Object DateTime can’t be converted to string”.