- 2 years ago 122
PHP Question

php failed to parse time string

I want to get difference between a date in db and the current date

That is my code :

$current_date = new \DateTime(date('Y-m-d H:i:s'));
foreach ($notifs as $notif) {
$created_notif = new \DateTime($notif->created);
$diff = date_diff($current_date, $created_notif);
if ($diff->y > 0) {
$notif->time = $diff->y . " year";

And this is the error that i got :

DateTime::__construct(): Failed to parse time string (17/05/2016
08:54) at position 0 (1):

And to don't say that i havent searched i tiried

Some thing like this :

$format = 'Y-m-d H:i:s';
$current_date = new \DateTime(date($format));
foreach ($notifs as $notif) {
$created_notif =\DateTime::createFromFormat($format,$notif->created);
$diff = date_diff($current_date, $created_notif);//line 32
debug($created_notif);//line 33

That's what i got :

Warning (2): date_diff() expects parameter 2 to be DateTimeInterface,
boolean given [APP/Controller\AdminController.php, line 32]

\src\Controller\AdminController.php (line 33)


Please i need your help

Answer Source

I assume, the $notif->created is 17/05/2016 08:54 so at that point you should use

$created_notif = \DateTime::createFromFormat('d/m/Y H:i', $notif->created);

This is why you not get a DateTime object and this is why date_diff not works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download