I am trying to determine whether a DateTime
exactly coincides with a possible occurance of a DateInterval
. The intervals I'm using need to allow for 'Nth Xday of next month' type format specifications and I'm not sure such a thing is possible given those conditions.
My basic idea was to invert the DateInterval
, apply it to a clone of the original DateTime
, put it back as it was, apply again and then check if the two DateTime
instances were equal. If so, it occurs exactly on the interval:
public static function dateFallsOnPeriod(DateTime $date, DateInterval $interval)
{
$compare = clone $date;
// invert the period, apply it to the date, uninvert & then reapply
$interval->invert = 1;
$compare->add($interval);
$interval->invert = 0;
$compare->add($interval);
return $date == $compare;
}
This seemed to apply the interval twice in the same direction, and so I tried again using ->sub()
and ->add()
, resulting in a fatal error "DateTime::sub(): Only non-special relative time specifications are supported for subtraction". It seems like this kind of functionality isn't implemented at all.
Does anyone have better ideas, in lieu of the ugly & inefficient solution of choosing an offset well behind the start date and iterating forward until we've matched it or gone past?
thanks in advance!