Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How we can add two date intervals in PHP
<?php
/**
* How we can add two date intervals in PHP
* @link http://stackoverflow.com/q/11556731/367456
* @link http://codepad.viper-7.com/oBW2le
*
* NOTE: This code is rough.
*/
header("Content-Type: text/plain;");
class MyDateInterval extends DateInterval
{
/**
* @param DateInterval $from
* @return MyDateInterval
*/
public static function fromDateInterval(DateInterval $from)
{
return new MyDateInterval($from->format('P%yY%dDT%hH%iM%sS'));
}
public function add(DateInterval $interval)
{
foreach (str_split('ymdhis') as $prop) {
$this->$prop += $interval->$prop;
}
$this->i += (int)($this->s / 60);
$this->s = $this->s % 60;
$this->h += (int)($this->i / 60);
$this->i = $this->i % 60;
}
}
$a = new DateTime('14:25');
$b = new DateTime('17:30');
$interval1 = $a->diff($b);
echo "interval 1: ", $interval1->format("%H:%I"), "\n";
$c = new DateTime('08:00:00');
$d = new DateTime('13:07:33');
$interval2 = $c->diff($d);
echo "interval 2: ", $interval2->format("%H:%I"), "\n";
$intervalSum = MyDateInterval::fromDateInterval($interval1);
foreach (range(1, 10) as $i) {
$intervalSum->add($interval2);
printf("#%02d Total interval: %s\n", $i, $intervalSum->format("%H:%I"));
}
interval 1: 03:05
interval 2: 05:07
#01 Total interval: 08:12
#02 Total interval: 13:20
#03 Total interval: 18:27
#04 Total interval: 23:35
#05 Total interval: 28:42
#06 Total interval: 33:50
#07 Total interval: 38:57
#08 Total interval: 44:05
#09 Total interval: 49:12
#10 Total interval: 54:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.