How do I find the hour difference between two dates in PHP?

You can convert them to timestamps and go from there:

$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);

Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.


You can use DateTime class also -

$d1= new DateTime("06-08-2015 01:33:26pm"); // first date
$d2= new DateTime("06-07-2015 10:33:26am"); // second date
$interval= $d1->diff($d2); // get difference between two dates
echo ($interval->days * 24) + $interval->h; // convert days to hours and add hours from difference

As an addition to accepted answer I would like to remind that \DateTime::diff is available!

$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);

/**
 * @var \DateInterval $diff
 */
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise

\DateInterval documentation.

Tags:

Datetime

Php

Date