I am trying to determine the number of date intervals between two dates. The interval could be a number of months, days, hours or whatever the user has chosen.
At the moment I have a function using recursion, however, this will break if there have been more than 100 intervals between the two points, due to the recursive nesting limit.
private static function findCurrentInterval($initialStartTimestamp, $intervalStrtotimeFormat, $now = null, $period = 1)
{
if (is_null($now)){
$now = time();
}
$endOfCurrentInterval = strtotime($intervalStrtotimeFormat, $initialStartTimestamp);
if ($now > $initialStartTimestamp && $now < $endOfCurrentInterval){
return new self($period);
}else{
# increment the period ID tracking variable
$period++;
return self::findCurrentInterval($endOfCurrentInterval, $intervalStrtotimeFormat, $now, $period);
}
}
All I need out of it is an integer value that represents which period of time intervals we are in currently, i.e. if it is set to a 7 day interval, and 20 days have passed between the start point and now, it would return '3', because we'd be into the 3rd period.
Is there a way of doing this without recursion, perhaps using DateInterval?
N.B. this would be really straightforward if it was limited to days or hours - but it needs to support months, which can have variable lengths.
This seems to work:
Examples:
Outputs:
And:
Outputs: