I have got a script that repeats activitities. When the repeat settings are:
repeat "the 2nd tuesday every 2 months, stop at 5 instances" (like google calendar would do).
I can accomplish "the 2nd tuesday every 2 months" with the script below:
<?php
$pubDay = 19;
$pubMonth = 7;
$pubYear = 2017;
$repeatMonths = 2;
$newMonth = $pubMonth;
$newYear = $pubYear;
$raisedMonth = $pubMonth + $repeatMonths;
if ( $raisedMonth > 12 ) {
$newMonth = ($raisedMonth) % 12; // off 12 at starts at 1
$newYear = $pubYear + 1;
} else {
$newMonth = $raisedMonth;
}
$occurenceInMonth = ceil($pubDay / 7); // determine the weekday occurence in the month (b.e. the "2nd thursday")
$dates = array();
foreach (getWeekDayDates($pubDow, $newYear, $newMonth) as $weekdaydate) {
$dates[] = $weekdaydate->format("Y-m-d");
}
// we need the x occurence (-1)
$newPubDate = isset($dates[$occurenceInMonth -1]) ? $dates[$occurenceInMonth -1] . " " . $pubHour . ":" . $pubMin : "";
echo $newPubDate;
function getWeekDayDates($weekday, $y, $m) {
return new DatePeriod(
new DateTime("first " . $weekday . " of $y-$m"),
DateInterval::createFromDateString('next ' . $weekday),
new DateTime("next month $y-$m-01")
);
}
?>
This works like a charm.
But now i need to check wether it is the 5th instance, starting at 17-9-2016. My script is now like this:
// get the end date
$startdate = "2016-09-17";
$repeatMonths = 2;
$endTime = strtotime($startdate . " +" . ($repeatMonths * $reps) . " months");
if ( $endTime >= strtotime($newPubDate) ) {
$doRepeat = true;
}
But this can go wrong!
By example when the repetitons starts (startddate) at saturday 4-7 and it repeats every first sunday. When the sunday in the last repetition is on the 6th of the month. The script above returns false, but it shouldnt't.
How can i check on a simple way if it is the 5th occurence?