Skip to content

Instantly share code, notes, and snippets.

@jakefolio
Created October 17, 2016 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakefolio/7cd6f5194eca93a280652773e3b38648 to your computer and use it in GitHub Desktop.
Save jakefolio/7cd6f5194eca93a280652773e3b38648 to your computer and use it in GitHub Desktop.
Add duration strings into DateInterval
<?php
$durations = [
'2:01:05',
'2:35:25',
'1:45:01',
];
function getDateIntervalFromString($duration) {
$i = 0;
$totalSeconds = array_reduce(
array_reverse(explode(':', $duration)),
function ($prev, $time) use (&$i) {
if ($prev === null) {
return (int) $time;
}
$i++;
return $prev + (pow(60, $i) * (int) $time);
}
);
return DateInterval::createFromDateString("{$totalSeconds} seconds");
}
$startTime = new DateTimeImmutable();
$endTime = array_reduce(
$durations,
function ($prev, $item) {
return $prev->add(getDateIntervalFromString($item));
},
$startTime
);
echo $startTime
->diff($endTime)
->format('%H:%I:%S');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment