1

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 DateTime::createFromFormat

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
                die();

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)

false

Please i need your help

12
  • why *\* as prefix of DateTime?? Commented May 17, 2016 at 10:13
  • @FrayneKonok - namespacing Commented May 17, 2016 at 10:13
  • If i don't use it he don't know it Commented May 17, 2016 at 10:13
  • So what is the format of $notif->created? Looks like dd/mm/yyyy Commented May 17, 2016 at 10:14
  • Thanks @MarkBaker. Commented May 17, 2016 at 10:14

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

var_dump($created_notif) it should be false.
I changed the format as you say d/m/Y H:i and i got the same error
what you get from var_dump($notif->created)?
@MateiMihai '17/05/2016 08:54' The problem is from ` $format = 'd/m/Y H:i'; $current_date = new \DateTime($format);`
@MateiMihai Thank you for fixing the misspell. What a shame :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.