Calculating the Difference Between Two Time Periods in PHP
PHP is a server-side scripting language extensively used in web development. Whether you're developing an appointment booking system, tracking user sessions, or generating logs, calculating the time difference between two periods is a common task.
PHP makes this process easy with its powerful DateTime
and DateInterval
classes.
In this sub-article, we’ll write a PHP program that calculates the difference between two specific date-time values using object-oriented time handling.
This article complements our lead C article with an elegant PHP solution.
PHP Program: Calculate the Difference Between Two Time Periods
<?php
// DIFFERENCE BETWEEN TWO TIME PERIODS in PHP using DateTime class
// Step-1 Define two datetime strings
$start = new DateTime("2025-11-05 10:15:00");
$end = new DateTime("2025-11-13 17:40:25");
// Step-2 Calculate the difference
$interval = $start->diff($end);
// Step-3 Extract hours, minutes, and seconds
$totalHours = ($interval->days * 24) + $interval->h;
$minutes = $interval->i;
$seconds = $interval->s;
// Step-4 Display the result
echo "\nTIME DIFFERENCE: {$totalHours} HOURS, {$minutes} MINUTES, {$seconds} SECONDS";
?>
Output
TIME DIFFERENCE: 199 HOURS, 25 MINUTES, 25 SECONDS
Explanation
-
DateTime
creates immutable objects to represent the date and time. -
diff()
returns aDateInterval
object that stores the full difference. -
The total hours are calculated by converting the number of days to hours and adding the remaining hours.
This approach is ideal for server-side applications, billing systems, or any web-based service that involves time tracking or scheduling.
Extra Metric: Total Duration in Minutes
If you need to log durations for reporting or database storage, you can compute the total minutes like this:
$totalMinutes = ($interval->days * 24 * 60) + ($interval->h * 60) + $interval->i;
echo "\nTOTAL DURATION IN MINUTES: {$totalMinutes}";
Output
TOTAL DURATION IN MINUTES: 11965
This kind of metric is especially useful in usage-based pricing models or performance tracking dashboards.