1

Suppose we have a time interval like this:

$interval = new \DateInterval('P1M');

Is there a way to calculate how many such intervals will occur in a year? I am specifically looking for something like division of the intervals [which does not work like this]:

$interval = new \DateInterval('P1M');
$year = new \DateInterval('P1Y');
$ans = $year/$interval; //returns false

Answer: 12

Tanner
  • 13
  • 2
  • You have the problem of leap years and leap seconds... what do you think of these? – Prof. Falken Oct 13 '14 at 18:12
  • This is insurance mathematics so I suppose leap seconds are not that much of a concern. Leap year on the other hand should be accounted for, such as when calculating using DateInterval('P15D') it could become an issue. – Tanner Oct 13 '14 at 18:17
  • You're trying to divide one object by another, that simply doesn't work. – Mark Baker Oct 13 '14 at 18:27
  • @MarkBaker, I interpret it as an example of what he wants to achieve... – Prof. Falken Oct 13 '14 at 18:30
  • Yes, it is an illustration only, I know it doesn't work, even said so in the question. – Tanner Oct 13 '14 at 19:01

1 Answers1

1

You can't do this by simple mathematical operations with objects, but loop and count will work

$interval = new \DateInterval('P1M');
$now = new \DateTime();
$year = new \DateInterval('P1Y');
$nowYear = clone $now;
$nowYear->add($year);

$intervals = 0;
do {
    $now->add($interval);
    ++$intervals;
} while ($now < $nowYear);

var_dump($intervals);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Yes, that should work if we want to calculate for current year only. If we want for any other year, just enter that year into DateTime() I guess? I was going to write that answer, but my PHP was rusty so I just had time to fire up Emacs while you already posted your answer. :) +1 – Prof. Falken Oct 13 '14 at 18:33
  • You'd simply modify the value by setting an actual date in `$now`, in most cases, it wouldn't really matter (though spanning a leap year Feb 29th might make a difference in some cases); but the method should work with any arbitrary intervals, not simply years and months.... though the answer will always be "floored" to an integer result – Mark Baker Oct 13 '14 at 18:35
  • Thank you, this is probably the answer. I was looking for something more elegant using DateIntervals only, but that probably isn't possible. – Tanner Oct 13 '14 at 19:03
  • I tried it using P1D for the year 2016 and leap year is calculated correctly. – Tanner Oct 13 '14 at 19:13