Created
July 19, 2012 09:12
-
-
Save hakre/3142405 to your computer and use it in GitHub Desktop.
How we can add two date intervals in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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")); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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