Why can't I access DateTime->date in PHP's DateTime class?

This is a known issue.

Date being available is actually a side-effect of support for var_dump() here – [email protected]

For some reason, you're not supposed to be able to access the property but var_dump shows it anyways. If you really want to get the date in that format, use the DateTime::format() function.

echo $mydate->format('Y-m-d H:i:s');

Update: The behaviour has changed in PHP7.3, the original answer doesn't work anymore. To get the same results with all PHP versions, incl. >=7.3, you can use the following code:

$dt = new DateTime();
$date = $dt->format('Y-m-d\TH:i:s.v');

For the record, the original answer:

Besides calling DateTime::format() you can access the property using reflection:

<?php

$dt = new DateTime();
$o = new ReflectionObject($dt);
$p = $o->getProperty('date');
$date = $p->getValue($dt);

This is slightly faster than using format() because format() formats a timestring that has already been formatted. Especially if you do it many times in a loop.

However this is not a documented behaviour of PHP, it may change at any time.


As noted by the other answers, it is an issue with PHP which is unresolved as of today but if it is a 'side effect' of var_dump() I am not so sure..

echo ((array) new DateTime())['date']; // Works in PHP 7.

What I am sure about is that if the properties of DateTime where meant to be used by us it would have been made available. But like many internal classes they are not and you shouldn't rely on "hacky" or "glitchy" methods to fix your code. Instead you should use their API.

echo (new DateTime())->format('Y-m-d H:i:s');

If you are not satisfied you can extend the class or perhaps use Carbon that extends it for you.

echo (new Carbon())->toDateTimeString();

If you wounder how var_dump() creates a fake output of an object take a look at __debugInfo()

Tags:

Datetime

Php