Sunil Shenoy Sunil Shenoy - 1 year ago 80
PHP Question

Get Weekend Dates in php

I am working on a php application which requires that I extract the dates of the weekends between two dates and then insert them as single records in the mysql database.

I was thinking if there was a simpler way of doing it, rather than going through the loop between start date and end date and for each date checking if

date('l', strtotime($date))
returns "Saturday" or "Sunday"

Thanks for your time


Answer Source

If you're using an older installation of PHP (or don't have the DateTime class):

$now = strtotime("now");
$end_date = strtotime("+3 weeks");

while (date("Y-m-d", $now) != date("Y-m-d", $end_date)) {
    $day_index = date("w", $now);
    if ($day_index == 0 || $day_index == 6) {
        // Print or store the weekends here
    $now = strtotime(date("Y-m-d", $now) . "+1 day");

We loop through the date range and check to see if the day is a 0 or 6 index (Sunday or Saturday).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download