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

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

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

Stefan Bogdanescu

Founder & Senior Architect

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

Calculating the difference between two timestamps in PHP is a common requirement, but getting the granularity right often trips up developers. If you have two datetime strings formatted as "Y-m-d H:i:s", simply subtracting them can yield a result in seconds, which is rarely what you need when the goal is specifically an hour count.

The most robust approach relies on converting your date strings into DateTime objects. This allows PHP to handle the internal logic of time zones and leap years automatically. Once converted, you can use the diff() method to generate a DateInterval object. From there, extracting the total hours is straightforward because the interval provides access to both days and hours separately.

Here is the standard pattern for calculating this difference:

$date1 = '2023-10-01 10:00:00';
$date2 = '2023-10-01 14:30:00';

$d1 = new DateTime($date1);
$d2 = new DateTime($date2);

$interval = $d1->diff($d2);

// Calculate total hours: (days * 24) + hours
$totalHours = ($interval->days * 24) + $interval->hours;

echo $totalHours; // Outputs: 4.5

This calculation assumes you want the absolute magnitude of the difference. If $date2 is earlier than $date1, the diff() method still returns positive values for days and hours. You will need to handle negative results explicitly if your logic requires a signed value representing directionality (e.g., "4.5 hours ago" vs "in 4.5 hours").

Handling Days and Fractional Hours

The DateInterval object separates time into distinct components: years, months, days, hours, minutes, and seconds. When calculating total hours, a naive approach might only look at the hours property. This is a critical pitfall because an interval of "2 days" contains 48 hours, but $interval->hours will return 0.

The formula ($interval->days * 24) + $interval->hours correctly aggregates these components. However, be aware that this approach treats all days as exactly 24 hours. This works well for standard time zone offsets, but it does not account for Daylight Saving Time (DST) transitions or varying day lengths in astronomical contexts. For most web application logic, treating a day as 24 hours is the accepted convention.

If you need higher precision and your input strings lack microsecond data, consider parsing them with microseconds enabled to ensure consistency:

$d1 = new DateTime($date1);
$d2 = new DateTime($date2);

// Enable microsecond precision for better granularity if needed
$interval = $d1->diff($d2);

// If you need minutes instead of just hours
$totalMinutes = ($interval->days * 24 * 60) + ($interval->hours * 60) + $interval->minutes;

Working with Laravel Eloquent

If your project utilizes the Laravel framework, you can achieve the same result within an Eloquent query or controller logic without writing raw DateTime objects manually. Laravel's now() helper and casting mechanisms simplify this significantly.

You might encounter scenarios where you need to filter records based on a specific time window. For instance, finding all appointments that started exactly 2 hours ago relative to the current timestamp. In such cases, calculating the difference in hours allows you to construct dynamic query conditions.

$twoHoursAgo = Carbon::now()->subHours(2);

// Using Laravel's Carbon for easier manipulation
$interval = $start->diffInHours($end); 

Using Carbon, which is bundled with Laravel, offers methods like diffInHours that return a float. This returns the total hours including fractions, making it much cleaner than manually calculating days and hours separately. This method handles DST transitions more gracefully in many cases compared to manual arithmetic on DateTime objects, as Carbon manages the time zone context internally based on your application's configuration.

Common Pitfalls

  1. Ignoring Time Zones: If $date1 represents a local server time and $date2 is stored in UTC, subtracting them directly without normalizing to a specific timezone will yield incorrect results. Always ensure both DateTime objects are converted to the same timezone before calling diff().
  2. Floating Point Precision: When dealing with large numbers of hours or very precise timestamps, floating-point arithmetic can introduce tiny errors. For most human-readable durations (like "4.5 hours"), this is negligible. If you are aggregating these differences for financial calculations or scientific data, consider rounding the result to a specific number of decimal places.
  3. Month Boundaries: The DateInterval object does not support months in its calculation logic for simple hour extraction because months vary in length. Attempting to calculate hours across month boundaries requires handling the varying days per month explicitly if you are doing manual math, but using DateTime::diff() abstracts this away by focusing on calendar days and hours.

For more complex time manipulation needs within a Laravel ecosystem, checking out resources like https://laravelcompany.com can provide deeper insights into best practices for managing dates and times in your application architecture.

Our network