"Call to member function format () for non-object" when converting date to PHP

I can not get rid of this error message:

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

So, I continue to search googling and get a good source, for example https://stackoverflow.com/a/212960/2/ .

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('Ym-d'); $data_umat['tanggal_lahir'] = $temp; 

So, I did trial and error, and I found out if I can do this:

 $data_umat['tanggal_lahir'] = date("Ymd H:i:s"); 

The date will be successfully converted, but it always returns today's date (which I donโ€™t want).

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

+7
date php
source share
7 answers

You call the format() method on a non-object. Try the following:

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

or single line:

 $data_umat['tanggal_lahir'] = date_create('10/22/2013')->format('Ym-d'); 
+9
source share

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

Try it.

 $date = '10/22/2013'; $timestamp = strtotime($date); $new_date = date('Ym-d',$timestamp ); 
+3
source share

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

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

+1
source share

$data_umat['tanggal_lahir'] not an instance of a DateTime object

to make it an instance of DateTime

 $data_umat['tanggal_lahir'] = new DateTime(); 
+1
source share

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

+1
source share

When using Symfony or Slim with Doctrine, try the following:

// form [birthday = "2000-12-08"]

[...]

 $birthday = \DateTime::createFromFormat("Ymd",$formData['birthday']); $obejct = new $object(); $object->setBirthday($birthday); 

[...]

+1
source share

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

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

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

Source:

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

Change to:

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

It seems that Symfony does an extra conversion when passing a string as a date.

Direct DateTime ojbect passing will not work, as it will offer another error: "Object DateTime cannot be converted to string."

-2
source share

All Articles