1

I need to check the given period will at least be covers the one night of the weekend(saturday night or sunday night) (refer the wiki article about the rule).

I found this question that, how to check the date whether it is fall on weekend or not,

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

But still I am struggle with how to implement a function to get following sample results for given periods,

Sample periods and results:

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)

The rule should wither start date is falls on weekend or end date is falls on sunday or the period covers at a full weekend.

Community
  • 1
  • 1
Janith Chinthana
  • 3,792
  • 2
  • 27
  • 54

1 Answers1

2

I presume you're looking for something like this:

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;   
}

Be warned, there isn't on validation on what the user passes in. You may want to add a check that a valid DateTime object was passed for each parameter.

Hope it helps.

Edit: Updated the solution with @honzalilak's feedback.

Mikey
  • 2,606
  • 1
  • 12
  • 20
  • 1
    Small improvement: you can return true in the if part instead of assigning it to variable and end the loop right away when there is a match with weekend. – honzalilak Jan 19 '16 at 14:39