Find every Sunday between two dates

后端 未结 4 1318
无人及你
无人及你 2020-12-10 09:08

I have $fromdate and $todate variables. I want a function that can calculate the dates of each Sunday existing in between $fromdate an

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 09:31

    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's in year 2010:

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

    The reuslt:

    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
    )
    

提交回复
热议问题