Find every Sunday between two dates

I have variables $fromdateand $todate. I want a function that can calculate the dates of every Sunday existing between $fromdateand $todatein PHP.

+3
source share
4 answers

Assuming these are date objects, start with $ fromdate, add one day to it until that date is on Sunday, and until the date is before $ todate. Add 7 days to every Sunday you find, add this date and continue until the new date is up to $ todate. Keep track of each date found this way.

+11
source

Use this function:

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

The function call to get dates for all Sunday in 2010:

$dateArr = getDateForSpecificDayBetweenDates('2010-01-01', '2010-12-31', 0);

print "<pre>";
print_r($dateArr);

Repeat:

Array
(
    [0] => 2010-01-03
    [1] => 2010-01-10
    [2] => 2010-01-17
    [3] => 2010-01-24
    [4] => 2010-01-31
    [5] => 2010-02-07

     ................
     ................
     ................

    [47] => 2010-11-28
    [48] => 2010-12-05
    [49] => 2010-12-12
    [50] => 2010-12-19
    [51] => 2010-12-26
)
+8
source

function getDateForSpecificDayBetweenDates($start, $end, $weekday = 0){

$weekdays="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday";

$arr_weekdays=split(",", $weekdays);
$weekday = $arr_weekdays[$weekday];
if(!$weekday)
    die("Invalid Weekday!");

$start= strtotime("+0 day", strtotime($start) );
$end= strtotime($end);

$dateArr = array();
$friday = strtotime($weekday, $start);
while($friday <= $end)
{
    $dateArr[] = date("Y-m-d", $friday);
    $friday = strtotime("+1 weeks", $friday);
}
$dateArr[] = date("Y-m-d", $friday);

return $dateArr;
}

...

$dateArr = getDateForSpecificDayBetweenDates("Today", "+1 year", 0); // 0 Sun, 1 Mon, etc.

$startand $enddates will accept anything that supports strtotime().

+3
source

PHP date () and mktime () functions should get you there!

0
source

All Articles