Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

php

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.

like image 453
Blaze Tama Avatar asked Oct 07 '13 08:10

Blaze Tama


6 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');
like image 117
Glavić Avatar answered Nov 14 '22 23:11

Glavić


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 );
like image 38
dashbh Avatar answered Nov 15 '22 00:11

dashbh


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

use to make it instance of DateTime

$data_umat['tanggal_lahir'] = new DateTime();
like image 32
Shushant Avatar answered Nov 15 '22 00:11

Shushant


$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

like image 28
bear Avatar answered Nov 14 '22 23:11

bear


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

like image 44
mak-hack Avatar answered Nov 15 '22 00:11

mak-hack


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);

[...]

like image 38
Drausio Lucas Avatar answered Nov 14 '22 23:11

Drausio Lucas