Question

When I try to output a DateTime object, it is literally printing the format, e.g.

Y-m-d H:i:s

Code

$db = new PDO('mysql:host=localhost;dbname=xxx;charset=utf8', 'xxx', 'xxx');
$dbTime = new DateTime(current($db->query('SELECT NOW()')->fetchAll(PDO::FETCH_COLUMN, 0)));
$myTime = new DateTime();
$diff = $myTime->diff($dbTime);
echo $diff->format('Y-m-d H:i:s');

From reading other questions and examples this should work so I'm confused why it's not.

Was it helpful?

Solution

The DateTime::diff method returns a DateInterval object. Your getting unexpected results because you are calling format on a DateInterval object which is different to the implementation on the DateTime object. see http://php.net/manual/en/dateinterval.format.php for more info on how to use it.

OTHER TIPS

The output from DateTime::diff() is a DateInterval object, which has rather different formatting Meanings.... in particular read about the overflow. Note also the use of % symbols to force format characters, otherwise they're treated as string characters

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top