Link to home
Start Free TrialLog in
Avatar of Robert Francis
Robert Francis

asked on

Number of hours between date in DB and now

Dealing with time is something I can't seem to wrap my head around.

Can someone please explain why this does not work:

While ($row2 = sqlsrv_fetch_array($results2)) {
$q_date = $row2["q_date"];
$cdate = date('Y-m-d H:i:s');
$datetime1 = date_create($cdate);
$datetime2 = date_create($q_date);
$interval = date_diff($datetime1, $datetime2);
$ddiff = $interval->format('%H:%I hours');

<td><?php echo $ddiff;?></td>

Open in new window


Here are the errors:

Warning: date_create() expects parameter 1 to be string, object given in C:\inetpub\wwwroot\portal2\rfq_admin_test.php on line 50

Warning: date_diff() expects parameter 2 to be DateTimeInterface, boolean given in C:\inetpub\wwwroot\portal2\rfq_admin_test.php on line 51

Fatal error: Call to a member function format() on boolean in C:\inetpub\wwwroot\portal2\rfq_admin_test.php on line 52
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Please use var_dump() to print the value of the $q_date and $cdate variables and post the output here, thanks.
Avatar of Robert Francis
Robert Francis

ASKER

string(19) "2017-02-15 09:01:05" cdate

object(DateTime)#1 (3) { ["date"]=> string(26) "2017-02-15 07:06:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } q_date
Interesting... $q_date appears to be a DateTime object already!

So the strategy would be to make cdate into a DateTime object, then you can do the arithmetic using the two objects.
But the error states it wants it to be a string:

Warning: date_create() expects parameter 1 to be string
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
But the error states it wants it to be a string
Yes, that makes sense.  The output of var_dump() shows us that one variable is a string and the other is an object.
Ray - That worked perfect. Thanks
Great!  When you're ever in doubt about what a variable contains, var_dump() is your friend!