reddish reddish - 4 months ago 15
PHP Question

How can I verify that a date range includes a weekend?

I have a date range that comes from MySQL, for example:
2016-01-05 to 2016-01-10. I would like to check if both Saturday and Sunday are inside that date-range, not necessarily consecutive. So far I have found:

function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}


So I would have to loop for every single day in the range to see if it's a weekend day.

Are there any better approaches?

Answer

You don't need to loop over all the days. You just need to know the length of the date range and the first day's day of the week.

Assuming you have two DateTime objects:

$start = new DateTime('2016-01-05');
$end = new DateTime('2016-01-10');

You can determine if a Saturday and Sunday are contained in the date range by checking if the length of the range plus the numeric weekday of the start date is greater than 6.

function includes_weekend (DateTime $start, DateTime $end) {
    return $start->diff($end)->format('%a') + $start->format('w') > 6;
}

format('%a') returns the total number of days in the DateInterval returned by diff, and format('w') returns the numeric day of the week (Sunday = 0).