首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查开始日期的第五次复发。在一个月中的特定工作日重复出现

检查开始日期的第五次复发。在一个月中的特定工作日重复出现
EN

Stack Overflow用户
提问于 2017-07-19 09:19:19
回答 1查看 32关注 0票数 0

我有一个重复活动的剧本。当重复设置为:

每两个月重复一次“第二个星期二,在5个实例”(就像谷歌日历那样)。

我可以用下面的脚本来完成“每两个月第二个星期二”:

代码语言:javascript
复制
<?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开始。我的剧本现在是这样的:

代码语言:javascript
复制
// 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,但它不应该返回。

如果是第五次发生,我怎样才能检查一种简单的方式?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-19 13:19:27

我将创建一个数组,该数组保存下5个“每月第二个星期二”的DateTime对象:

代码语言:javascript
复制
$startdate = new \DateTime('second tue of february 2017');

$dates = array();
$repetitions = 5;
for ($i=0; $i<$repetitions; $i++) {
    $dates[] = clone $date->modify('+1 month');
}

使用这个数组应该很容易检查日期是否到达。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45186183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档