2

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
hungrykoala
  • 1,083
  • 1
  • 13
  • 28
  • $diff is a object here, which gives difference in year,month,weeks,day,hour,minute, you are accessing only hours here, print the complete $diff object, then you will get the correct value – RAUSHAN KUMAR Jul 10 '17 at 06:10
  • @RAUSHANKUMAR So I have to convert the days into hours as well to get the full hour difference? – hungrykoala Jul 10 '17 at 06:12

3 Answers3

3

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
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
  • I see, So I have to look for the day as well. Maybe that is why it was working for my other date range since the difference was only 22 hours. Thank you for this. – hungrykoala Jul 10 '17 at 06:13
0

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'
anil funde
  • 93
  • 1
  • 8
0

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;
Manav Sharma
  • 187
  • 1
  • 8