2

I have two dates in 24 hour format

$fulldate_hour_start    = "2013-11-11 18:16:00 ";
$fulldate_hour_end      = "2013-11-11 23:30:00 ";

and I subtracted them using this

$Hours = number_format((((strtotime($fulldate_hour_end) - strtotime($fulldate_hour_start)) / 60) / 60),2);

and the result is 5 hours and 23 minutes. it should be 5 hours and 14 minutes. What is my error?

kevin_marcus
  • 277
  • 1
  • 5
  • 19
  • possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Glavić Nov 11 '13 at 11:30

3 Answers3

4

Try this :

$date1 = new DateTime("2013-11-11 18:16:00");
$date2 = new DateTime("2013-11-11 23:30:00");
$interval = $date1->diff($date2);
echo "difference " . $interval->h . " Hours, " . $interval->i." Mintues, ".$interval->s." seconds "; 
vascowhite
  • 18,120
  • 9
  • 61
  • 77
Mahmood Rehman
  • 4,303
  • 7
  • 39
  • 76
0

You're dividing by 3600 to convert from seconds to hours and then using number_format to render the result with two decimal places.

The result of the expression was:

5.23

Which is indeed approximately 5 hours and 14 minutes. (Remember that an hour has 60 minutes.)

Rather than do this, you should keep the value in seconds, and then use a function to convert it to a human readable format. One possibility is date_diff; the linked SO question has many others.

Community
  • 1
  • 1
Michael Hampton
  • 9,737
  • 4
  • 55
  • 96
0

Since an hour consist of 60, not 100, minutes, 5.23 hours is 5 hours and 13.8 minutes. The 0.2 hour mismatch is due to rounding the real value to two decimals to get 0.23.

0.23 * 60 = 13.8
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294