Reputation: 262
$date1 = new DateInterval('PT100S'); //100 seconds
$date2 = new DateInterval('PT20S'); //20 seconds
How to make $date1 - $date2
? I've searched on google for hours.
Upvotes: 2
Views: 456
Reputation: 59701
This should work for you:
Here I simply get the array_intersect_key()
from the defined $keys
, with both DateInterval objects. So that I then can loop through both arrays with array_map()
and subtract the values. With the calculated values I create a new DateInterval
object, which I then return.
<?php
$date1 = new DateInterval('PT100S');
$date2 = new DateInterval('PT20S');
function subtractDateIntervals($intervalOne, $intervalTwo) {
$keys = ["y", "m", "d", "h", "i", "s"];
$intervalArrayOne = array_intersect_key((array)$intervalOne, array_flip($keys));
$intervalArrayTwo = array_intersect_key((array)$intervalTwo, array_flip($keys));
$result = array_map(function($v1, $v2){
return abs($v1 - $v2);
}, $intervalArrayOne, $intervalArrayTwo);
return new DateInterval(vsprintf("P%dY%dM%dDT%dH%dM%dS", $result));
}
var_dump(subtractDateIntervals($date1, $date2));
?>
output:
object(DateInterval)#3 (15) {
//...
["s"]=>
int(80)
//...
}
Upvotes: 1