Calculate Difference Between Two Dates
Calculates the difference between two dates and returns days, hours, minutes, and direction.
Purpose
Calculates the difference between two dates and returns days, hours, minutes, and direction.
Snippet details
ContextDate TimeLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Calculate Difference Between Two Dates.
*
* Purpose:
* Calculates a readable interval between two date/time strings.
*
* @param string $start_date Start date/time.
* @param string $end_date End date/time.
* @param string $timezone_name PHP timezone name.
* @return array Date difference report.
*/
function ogSnippetCalculateDateDifference(string $start_date, string $end_date, string $timezone_name): array {
$timezone_name = trim($timezone_name);
if (in_array($timezone_name, timezone_identifiers_list(), true) === false) {
$timezone_name = 'UTC';
}
$timezone = new DateTimeZone($timezone_name);
$start = new DateTimeImmutable($start_date, $timezone);
$end = new DateTimeImmutable($end_date, $timezone);
$interval = $start->diff($end);
$direction = 'forward';
if ($interval->invert === 1) {
$direction = 'backward';
}
return array(
'days' => (int) $interval->days,
'hours' => (int) $interval->h,
'minutes' => (int) $interval->i,
'direction' => $direction
);
}
$difference_report = ogSnippetCalculateDateDifference('2026-07-02 09:00:00', '2026-07-04 12:30:00', 'America/New_York');
echo 'Mission interval days: '.$difference_report['days'];