Calculate number of hours between 2 dates in PHP

Calculate number of hours between 2 dates in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Calculate number of hours between 2 dates in PHP

Calculating the difference between two timestamps in PHP requires a precise understanding of how the language handles time data. The core mechanism relies on converting human-readable date strings into a standard numerical format known as Unix timestamps, or "epoch" seconds. Once both dates are represented as integers counting seconds from January 1, 1970, subtracting them yields the total elapsed time in seconds. This integer subtraction is the foundation for any duration calculation, whether you need minutes, hours, days, or milliseconds.

To achieve the specific requirement of finding the difference in hours, you must divide the resulting second count by 3600 (the number of seconds in an hour). However, this arithmetic operation alone does not account for timezone discrepancies if your input strings represent local times in different zones. The most robust approach is to normalize both dates to a single timezone before performing the calculation. This ensures that you are comparing absolute moments in time rather than relative wall-clock times, which prevents errors when dealing with events spanning midnight or crossing day boundaries.

Consider the specific scenario provided: determining the hours between 2006-04-12 12:30:00 and 2006-04-14 11:30:00. The expected result is 47 hours. To replicate this in modern PHP, you should instantiate DateTime objects for both values. This class provides a much safer environment than the legacy strtotime() function, particularly when dealing with edge cases involving daylight saving time transitions or invalid date formats.

$date1 = new DateTime('2006-04-12 12:30:00');
$date2 = new DateTime('2006-04-14 11:30:00');

// Set a specific timezone to ensure consistent calculation
date_default_timezone_set('UTC');
$date1->setTimezone(new DateTimeZone('UTC'));
$date2->setTimezone(new DateTimeZone('UTC'));

$diff = $date1->diff($date2);

// The diff() method returns a DateInterval object.
// To get the total hours, we calculate (days * 24) + fractional hours.
// Since the example implies a simple subtraction logic, 
// we can use the format string to parse the interval directly.

$hours = ($diff->days * 24) + $diff->h + ($diff->i / 60); // ignoring minutes for pure hour count

echo round($hours, 2); // Output: 47

In this implementation, we explicitly set the timezone to UTC. This is a critical step because DateInterval objects do not inherently store timezone offsets; they represent a duration. If your inputs are in different timezones, failing to normalize them first could result in an incorrect offset being applied or ignored, leading to results that deviate from reality. For instance, if one date represents 12:30 PM in New York and the other represents 12:30 PM in London, a naive calculation might treat them as occurring at the same absolute time, whereas they are actually separated by an hour.

The DateInterval object returned by the diff() method provides properties like days, h (hours), i (minutes), and s (seconds). To derive the total hours accurately, you sum the full days converted to hours (multiplied by 24) and add the remaining hours. The fractional part of the hour is derived from the minutes ($diff->i / 60). In many applications, rounding this final figure is preferable to maintaining decimal precision down to the second, as most business logic operates on whole hours or rounded blocks of time.

A common pitfall in date manipulation is assuming that string concatenation or simple subtraction of date strings works reliably. PHP will treat date strings as 0 if they are not valid timestamps, leading to silent failures or zero-duration results. Always validate your input strings or rely on the DateTime constructor, which throws a FormatException if the provided string cannot be parsed. This exception handling allows you to fail fast rather than silently returning incorrect data to your downstream logic.

For high-performance applications where object instantiation might become a bottleneck, converting strings directly to timestamps using (int)$dateString (via strtotime) and then dividing the difference by 3600 can be slightly faster. However, this method strips away timezone context entirely unless you manually parse the offset string into the calculation, which adds complexity without significant benefit for most use cases. The DateTime approach remains the industry standard due to its clarity, type safety, and ability to handle complex calendar logic like leap years and varying month lengths automatically.

Our network