PHP Function that Returns the Date for a Specific Day Between Two Given Dates

Here’s a PHP function that returns the date for a specific day between two given dates. The function takes two dates formatted as YYYY-MM-DD and creates an inclusive array of the dates between the from and to dates.

function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    $dateArr = array();

    do
    {
        if(date("w", $startDate) != $weekdayNumber)
        {
            $startDate += (24 * 3600); // add 1 day
        }
    } while(date("w", $startDate) != $weekdayNumber);


    while($startDate <= $endDate)
    {
        $dateArr[] = date('Y-m-d', $startDate);
        $startDate += (7 * 24 * 3600); // add 7 days
    }

    return($dateArr);
}

For example, to get a list of all Sundays between two dates use the above function as shown,

$dateArrSunday = getDateForSpecificDayBetweenDates('2016-01-01', '2016-12-31', 0);

You can then iterate through the dates in the following manner.

foreach($dateArrSunday as $date)
{
echo $date;
}

This content has been helpful to you?

Thanks for contributing!

Yes No