PHP date_diff返回错误的值来比较两个日期时间

I found this post that shows how to get the difference in hours between two dates.

The dates are: 2017-07-03 13:55:20 AND 2017-07-04 21:17:44

When I tried using this code it gives me wrong value:

$date1 = date_create('2017-07-03 13:55:20');

$date2 = date_create('2017-07-04 21:17:44');

$diff = date_diff($date1,$date2);

$hour = $diff->h;

returns 8 hours //incorrect

But this one gives me the correct value:

$hourdiff = round((strtotime('2017-07-03 13:55:20') - strtotime('2017-07-04 21:17:44'))/3600);
returns 31 hours //correct

You have to go this way:

<?php
$date1 = date_create('2017-07-03 13:55:20');
$date2 = date_create('2017-07-04 21:17:44');

$diff = date_diff($date1,$date2);

$hour = ($diff->d * 24) + $diff->h;
echo $hour;

demo: http://ideone.com/7SBfHn

The date_diff function gives you the difference as follow:

             y  m  d  h  m  s
-----------------------------
Date1:    2017-07-03 13:55:20
             |  |  |  |  |  |
Diff:        0  0  1  8  0 24
             |  |  |  |  |  |
Date2:    2017-07-04 21:17:44

you can leverage 'format' function of object returned by date_diff. (http://php.net/manual/en/function.date-diff.php)

Here is my solution leveraging format function-

$date1 = date_create('2017-07-03 13:00:00');

$date2 = date_create('2017-07-04 21:17:44');

$diff = date_diff($date1,$date2);

$hour =( $diff->format('%d')*24 + $diff->format('%h')) . '.' . $diff->format('%i') . 'mins';

echo $hour; // output = '32.17mins'

use this,

$d1= new DateTime("2017-07-03 13:55:20"); 
$d2= new DateTime("2017-07-04 21:17:44");
$interval= $d1->diff($d2);
echo ($interval->days * 24) + $interval->h;