Suppose I have one DateInterval that is 1 year, and another that is 3 months.
Is it possible to divide one by the other and get an answer of 4, that is, there are 4 intervals of 3 months in an interval of 1 year?
Suppose I have one DateInterval that is 1 year, and another that is 3 months.
Is it possible to divide one by the other and get an answer of 4, that is, there are 4 intervals of 3 months in an interval of 1 year?
You could just try converting your DateInterval
s to seconds and dividing that:
$dateInterval1 = new DateInterval('P1Y');
$dateInterval2 = new DateInterval('P3M');
$dateInterval1Secs = date_create('@0')->add($dateInterval1)->getTimestamp();
$dateInterval2Secs = date_create('@0')->add($dateInterval2)->getTimestamp();
var_dump($dateInterval1Secs / $dateInterval2Secs);
Of course, this is really precise, and this code outputs 4.0555555555556
Converting to seconds from Convert DateInterval object to seconds in php
Directly no, since DateInterval
is an object. Something like this could help based on this answer
$y = new DateTime('@0');
$x = new DateTime('@0');
$secondsOfYear = $y->add(new DateInterval('P1Y'))->getTimestamp();
$secondsOfThreeMonths = $x->add(new DateInterval('P3M'))->getTimestamp();
print_r([$secondsOfYear,$secondsOfThreeMonths,(int)($secondsOfYear/$secondsOfThreeMonths)]);
// output
Array
(
[0] => 31536000
[1] => 7776000
[2] => 4
)
Check it out on PHP Sandbox
Dates do not lend themselves easily to mathematical operations. We can just about do addition and subtraction, that's about it. Multiplication makes little sense (1 month times 12 months = 1 square-year?) but division can be understood as "how many of this interval are there?" which can be implemented by repeated subtraction.
Create a DateTimeImmutable
for now
. add
the first of the intervals you are trying to perform division on. Then, subtract
the second interval until you obtain a new date/time that is less than (or equal to) your original DateTimeImmutable
. Count how many times this takes. That's your division answer.