【问题标题】:How to loop over weeks and find the exact date of some days?如何循环数周并找到某些日子的确切日期?
【发布时间】:2017-11-30 10:44:33
【问题描述】:

我正在开发一个网站,用户可以在该网站上每 X 天创建一些事件(其中 X 是一周中某一天的名称)。然后,他需要输入他想在未来创建的事件数。

例如,用户选择每周一和周二,并决定创建 150 个事件。

这是我到目前为止所做的代码:

// Init the date counter            
$cpt_date_found = 0;

// Number of date to find
$rec_occ = 150;

// Init an ending date far in the future        
$endDate = strtotime('+10 years', time());

// Loop over the weeks
for($i = strtotime('Monday', strtotime(date("d.m.Y"))); $i <= $endDate; $i = strtotime('+1 week', $i)) {

    // -- Monday date found, create the event in the database

    $cpt_date_found++;

    // Break the loop if we have enough dates found
    if($cpt_date_found == $rec_occ) {
        break;
    }

}

此代码查找未来每个星期一的日期,并在达到用户指定的出现次数后中断循环。

我输入了一个远在未来的结束日期,以确保我可以在用户指定的出现次数结束之前中断循环。

首先,我不确定我的代码的“质量”...我知道打破循环不是最好的主意,我想知道另一种解决方案是否更适合我的需求。

那么,如果用户指定了几天(比方说,星期一、星期二和星期五),而不是重复循环更多次,有没有办法为每个提供的日期循环一次?

谢谢!

【问题讨论】:

标签: php date calendar recurrence


【解决方案1】:

以下代码将循环 5 年。对于这 5 年中的每一周,它将生成一个包含该周每一天的 DatePeriod。它会将这些日子中的每一天与您的预设数组与您正在寻找的日子进行比较。然后,您可以生成事件,之后代码将倒计时一定次数。如果计数器达到零,则完成。

$searchDates = array('Mon', 'Tue', 'Fri');
$amountOfTimes = 27;

$startDate = new DateTime();
$endDate = new DateTime('next monday');
$endDate->modify('+5 years');

$interval = new DateInterval('P1W');
$dateRange = new DatePeriod($startDate, $interval ,$endDate);

// Loop through the weeks
foreach ($dateRange as $weekStart) {
    $weekEnd = clone $weekStart;
    $weekEnd->modify('+6 days');

    $subInterval = new DateInterval('P1D');

    // Generate a DatePeriod for the current week
    $subRange = new DatePeriod($weekStart, $subInterval ,$weekEnd);
    foreach ($subRange as $weekday) {
        if (in_array($weekday, array('Mon', 'Fri', 'Sun'))) {
            // Create event

            // Countdown
            $amountOfTimes--;
        }

        if ($amountOfTimes == 0) {
            break;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多