0

I am trying to access a a property of this object:

    object(DateTime)#321 (3) {
  ["date"]=>
  string(26) "2016-08-02 12:45:01.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/London"
}

I have tried this:

$boo = aboveObject;
$boo->date;

I get this error:

 "Notice: Undefined property: DateTime::$date"

I have also tried this:

$foo = aboveObject;
$foo['date']

I get this error:

"Error: Cannot use object of type DateTime as array"

of course the second error makes more sense to me bur the first way i tried should be working...? any idea what is going on?

John
  • 1,595
  • 4
  • 21
  • 44

2 Answers2

2

You can get date by this way:

 $dateObj = new DateTime();
 echo $dateObj->format('Y-m-d H:i:s');
Jigar Pancholi
  • 1,209
  • 1
  • 8
  • 25
2

The date property does not normally exist in a DateTime object. It is only added by print_r or var_dump in order to show you the contents of the object. You can see this by doing:

$boo = new DateTime;
echo $boo->date;

Which will get you a "Notice: undefined property", and then:

$boo = new DateTime;
print_r($boo);        // or var_dump($boo);
echo $boo->date;

which will successfully echo the added date property.

This is obviously not the correct way to get at this "property", however. You should use the format method as others have suggested to output the date in any format you want.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80