Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theprincy/a6ad1655148760130c1c70eb69e55060 to your computer and use it in GitHub Desktop.
Save theprincy/a6ad1655148760130c1c70eb69e55060 to your computer and use it in GitHub Desktop.
This function calculates the difference in hours between 2 complete periods.
function calculateDifferenceBetweenTwoPeriods($start, $end) {
$start = new DateTime($start);
$end = new DateTime($end);
$interval = $start->diff($end);
//Uncomment the line below to see all the returned values for the difference.
//print_r($interval);
$hour = str_pad($interval->h, 2, '0', STR_PAD_LEFT);
$minute = str_pad($interval->i, 2, '0', STR_PAD_LEFT);
$second = str_pad($interval->s, 2, '0', STR_PAD_LEFT);
return $hour.':'.$minute.':'.$second;
}
$start = '2021-05-01 20:20:25';
$end = '2021-05-02 03:05:15';
$difference = calculateDifferenceBetweenPeriods($start, $end);
/*
The return is 06:44:50 hours.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment