Getting time difference between two times in PHP

Getting time difference between two times in PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Calculating time differences in PHP requires moving beyond simple string subtraction. When you store attendance times as time or datetime columns, your application is dealing with actual timestamps, but treating them purely as text often leads to logic errors. If an employee logs in at 09:01:00 and your policy cutoff is 09:00:59, a naive string comparison might fail depending on how the database returns the data. To get accurate results for late arrivals, you must normalize these values into a format PHP understands natively before performing arithmetic.

The core challenge in this attendance scenario is distinguishing between "on time" and "late." You have a constant threshold—09:00:59—and a variable login time fetched from the database. The goal is to return null if the login time falls within the acceptable window, but calculate the exact duration of lateness otherwise.

The most robust approach involves converting these values into Unix timestamps (seconds since the epoch). This abstracts away the complexity of date formats, timezones, and daylight saving adjustments. By using PHP's strtotime() function or the DateTime class, you transform human-readable strings like "09:01:00" into integers representing absolute time points. Once both values are integers, subtraction yields the difference in seconds.

Here is a practical implementation pattern using the DateTime class, which offers better precision and readability than raw timestamps for business logic:

$cutoff = new DateTime('09:00:59');
$loginTime = $row['login_time']; // Expected format: 'HH:mm:ss' or full datetime

// Ensure the login time is treated as today's date if only time is stored
if ($loginTime instanceof DateTime) {
    // If input includes date, use it directly
} else {
    $loginTime = (new DateTime())->setTimeFromTimeString($loginTime);
}

$difference = $cutoff->diff($loginTime)->invert ? 
              $cutoff->diff($loginTime)->format('%i minutes') : null;

However, a more direct arithmetic approach using DateTime::createFromFormat is often cleaner for strict time-only inputs:

$cutoffTime = DateTime::createFromFormat('H:i:s', '09:00:59');
$loginTime = DateTime::createFromFormat('H:i:s', $row['login_time']);

if ($cutoffTime && $loginTime) {
    // Subtract the times. Note: Direct subtraction of DateTime objects isn't possible,
    // so we usually convert to timestamps or use DateInterval.
    
    $interval = $cutoffTime->diff($loginTime);
    
    // Check if login was after cutoff (meaning late)
    // Since diff() always returns positive values based on start/end order, 
    // we compare the actual string values or timestamps first.
    
    $cutoffTimestamp = strtotime('09:00:59');
    $loginTimestamp = strtotime($row['login_time']);

    if ($loginTimestamp > $cutoffTimestamp) {
        $diffSeconds = $loginTimestamp - $cutoffTimestamp;
        
        // Format the result as HH:mm:ss for display
        $finalDiff = date('H:i:s', $diffSeconds);
        // If you prefer minutes only:
        // $finalDiff = ceil($diffSeconds / 60);
    } else {
        $finalDiff = null;
    }
}

A critical pitfall in this logic is handling the "on time" condition. The requirement states that logging in at 09:00:59 or earlier should result in null. This implies an inclusive upper bound for valid attendance. Your conditional check must strictly compare the incoming timestamp against the threshold. If you use string comparison directly, be wary of inconsistent database formats (e.g., 09:00:59 AM vs 09:00:59). Always rely on strtotime() or DateTime::createFromFormat to ensure consistent parsing regardless of minor input variances.

Another consideration is the granularity of your data. If your database column stores full datetime values (e.g., 2023-10-27 09:01:00), you don't need to strip the date portion before calculating the difference between times; the timestamp arithmetic handles it automatically. However, if you are strictly working with time-of-day data without date context, ensure that both timestamps represent the same day. Calculating a difference between 09:01:00 on Monday and 09:01:00 on Tuesday would yield zero seconds, which might mask a full day of absence if not handled carefully in your broader attendance logic.

For developers working within the Laravel ecosystem, this pattern translates cleanly into service methods or controllers. You can create a helper method that accepts the raw time string and returns the formatted difference or null, keeping your blade templates clean. This abstraction prevents repetitive timestamp calculations throughout your codebase.

By converting to timestamps first, you simplify the logic significantly. You avoid writing complex conditional branches for every possible date format variation. The trade-off is slightly less human-readable intermediate values (integers instead of dates), but the final output—formatted back to HH:mm:ss or minutes—is exactly what your UI needs to display late arrival penalties clearly.

Our network