How to Calculate Hours Between Two Dates in PHP

Problem:

You have to dates and you want to calculate hours between those two dates.

Solution:

In the following you’ll see two methods to finds out hour difference between two dates

Method 1: Using strtotime() function

Using strtotime() function to find out hours is two steps process

  1. Convert each date to its equivalent timestamp (as you know, timestamp is number of seconds since January 1 1970 00:00:00 UTC)
  2. Divide the timestamp by (60*60) to get the number of hours.

See the following example how it works-

<?php
$date1 = "2014-05-27 01:00:00";
$date2 = "2014-05-28 02:00:00";
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
echo "Difference between two dates is " . $hour = abs($timestamp2 - $timestamp1)/(60*60) . " hour(s)";
?>

[wpdm_file id=119]

Output:
Difference between two dates is 25 hour(s)

How it works:

Line 3:
We convert the first date to its timestamp.Line 4:
We convert the second date to its timestamp.Line 5:
As the difference between two dates might be negative, we use absolute function, abs(), to get the value only. Then, we divided it by 60*60 to get the hours.

 

Method 2: Using diff() method of DateTIme class from SPL

Calculating hours between two dates is 3 steps process-

  1. Convert each date to the DateTime object
  2. Calculate the day interval between two dates as object using diff() method.
  3. Convert the Day interval object to its equivalent number of hours using format() method.
<?php
$hour1 = 0; $hour2 = 0;
$date1 = "2014-05-27 01:00:00";
$date2 = "2014-05-28 02:00:00";
$datetimeObj1 = new DateTime($date1);
$datetimeObj2 = new DateTime($date2);
$interval = $datetimeObj1->diff($datetimeObj2);

if($interval->format('%a') > 0){
$hour1 = $interval->format('%a')*24;
}
if($interval->format('%h') > 0){
$hour2 = $interval->format('%h');
}

echo "Difference between two dates is " . ($hour1 + $hour2) . " hours.";
?>

[wpdm_file id=120]

Output:
Difference between two dates is 25 hour(s)

How it works:

Line 5-6:
We convert two dates to their respective DateTime objects.Line 7:
The diff() method subtracts $datetimeObj1 from $datetimeObj2 and returns as an object.Line 9-11:
Here, we check if the interval between two dates is more than 1 day. If so, we convert the day to hours by multiplying it by 24. Here, format(‘%a’) returns total number of days.

Line 12-14:
The hour difference might be less than 1 day. In that case we directly convert the interval object to hours. Here, format(‘%a’) returns total number of hours.

Line 16:
As the time difference between two dates might be day difference and hour difference between those, so we added the both of those to get the real hour difference.