给定期限至少包括周末的一晚

Given period at least covers one night on the weekend

我需要检查给定的时间至少包括周末的一个晚上(周六晚上或周日晚上)(参考 wiki article 有关规则)。

我发现this question,如何检查日期是否是周末,

function isWeekend($date) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || $weekDay == 6);
}

但我仍然在为如何实现一个函数来获得给定时间段内的样本结果而苦恼,

样本周期和结果:

04-01-2016 / 07-01-2016 : false
04-01-2016 / 09-01-2016 : false
04-01-2016 / 10-01-2016 : true (covers saturday night)
03-01-2016 / 07-01-2016 : true (covers sunday night)
04-01-2016 / 14-01-2016 : true (covers a full weekend)

规则应该是开始日期是周末或结束日期是星期日或期间涵盖整个周末。

我想您正在寻找这样的东西:

function coversWeekend($start, $end) {
    $weekend       = [0, 6]; // 0 for Sunday, 6 for Saturday.

    // Loop over the date period.
    while ($start < $end) {
        if (in_array($start->format('w'), $weekend)) {
            return true;
        }

        $start->modify('+1 day');
    }

    return false;   
}

请注意,没有对用户传入的内容进行验证。您可能需要添加检查以确保为每个参数传递了有效的 DateTime 对象。

希望对您有所帮助。

编辑: 根据@honzalilak 的反馈更新了解决方案。