-1

I have a database from which I extract this date/time value: 2018-01-19 09:50:54

I want to print how many hours and minutes passed since that date, with regard to current server time:

I try this code:

$prev_date = "2018-01-19 09:50:54" // extracted from DB

$date_now = date("Y-m-d H:i:s"); // 24-hour date-time, matches DB format

$interval = $prev_date->diff($date_now); // I saw this on another thread 

echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";

I get:

Fatal error: Call to a member function diff() on a non-object (on the $interval=.... line )

I guess it is some kind of formatting problem, how do I fix that?

rockyraw
  • 1,125
  • 2
  • 15
  • 36

1 Answers1

3

$prev_date is not a object. You need to transform to a DateTime object to use diff. Also, date() will return a string, you must use a DateTime object for this to be able to use diff function.

$prev_date = DateTime::createFromFormat('Y-m-d H:i:s', '2018-01-19 09:50:54');

$date_now = new DateTime(); // 24-hour date-time, matches DB format

$interval = $prev_date->diff($date_now); // I saw this on another thread 

echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
  • For testing I'm trying to echo '$date_now = new DateTime();' to see it really gives current server time, but I'm getting an error.. – rockyraw Jan 19 '18 at 17:02
  • `$date_now` is a object now. You can't "echo", try using `var_dump($date_now);` instead. Or you can use `echo $date_now->format('Y-m-d H:i:s');` – Felippe Duarte Jan 19 '18 at 17:31