我有一个重复活动的剧本。当重复设置为:
每两个月重复一次“第二个星期二,在5个实例”(就像谷歌日历那样)。
我可以用下面的脚本来完成“每两个月第二个星期二”:
<?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")
);
}
?>这就像一种魅力。
但是现在我需要检查一下这是否是第五次,从17-9-2016开始。我的剧本现在是这样的:
// get the end date
$startdate = "2016-09-17";
$repeatMonths = 2;
$endTime = strtotime($startdate . " +" . ($repeatMonths * $reps) . " months");
if ( $endTime >= strtotime($newPubDate) ) {
$doRepeat = true;
}但这可能会出错!
例如,当重复开始(开始日期)在星期六4-7,它重复每第一个星期天。当最后一次重复的星期日是在月6日的时候。上面的脚本返回false,但它不应该返回。
如果是第五次发生,我怎样才能检查一种简单的方式?
发布于 2017-07-19 13:19:27
我将创建一个数组,该数组保存下5个“每月第二个星期二”的DateTime对象:
$startdate = new \DateTime('second tue of february 2017');
$dates = array();
$repetitions = 5;
for ($i=0; $i<$repetitions; $i++) {
$dates[] = clone $date->modify('+1 month');
}使用这个数组应该很容易检查日期是否到达。
https://stackoverflow.com/questions/45186183
复制相似问题