24
votes

In one of my entities, I have a protected property called insert_date which is a datetime.

When I extract the data afterwards, I don't get the date as a string, I get an object. My var dump:

<pre class='xdebug-var-dump' dir='ltr'> <b>object</b>(<i>DateTime</i>)[<i>1560</i>] <i>public</i> 'date' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'2011-08-26 12:40:29'</font> <i>(length=19)</i> <i>public</i> 'timezone_type' <font color='#888a85'>=&gt;</font> <small>int</small> <font color='#4e9a06'>3</font> <i>public</i> 'timezone' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'Europe/London'</font> <i>(length=13)</i> </pre><pre class='xdebug-var-dump' dir='ltr'> <b>object</b>(<i>DateTime</i>)[<i>1571</i>] <i>public</i> 'date' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'2011-08-26 12:40:29'</font> <i>(length=19)</i> <i>public</i> 'timezone_type' <font color='#888a85'>=&gt;</font> <small>int</small> <font color='#4e9a06'>3</font> <i>public</i> 'timezone' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'Europe/London'</font> <i>(length=13)</i>

I tried:

foreach($dateObj as $date) {

}

But it doesn't extract ... How can I get the date property from this object? Even $insert_date->date doesn't work.

2

2 Answers

55
votes

use

if($dateObj)
{
    $dateObj->format('Y-m-d H:i:s');
}
15
votes

To make sure that your $dateObj is an actual datetime obj use:

if($dateObj instanceof \DateTime){
    $dateObj->format('Y-m-d H:i:s');
}

using "instanceof" checks that the object will have the required format function thus wont throw errors if it isnt.