PHP获取一个月内所有星期日的日期


php get dates for all sundays in a month

我希望能够提出一个php函数,在参数年、月和日,并以数组形式返回给定日期的日期。

例如

。假设函数是这样的:

function get_dates($month, $year, $day)
{
    ....
}

如果我像下面这样调用函数:

get_dates(12, 2011, 'Sun');
我应该得到一个包含值的数组:

2011-12-04
2011-12-11
2011-12-18
2011-12-25

函数代码是什么样子的?

示例

function getSundays($y,$m){ 
    $date = "$y-$m-01";
    $first_day = date('N',strtotime($date));
    $first_day = 7 - $first_day + 1;
    $last_day =  date('t',strtotime($date));
    $days = array();
    for($i=$first_day; $i<=$last_day; $i=$i+7 ){
        $days[] = $i;
    }
    return  $days;
}
$days = getSundays(2016,04);
print_r($days);

例如,您可能想要找出月1日的工作日,这将帮助您获得第一个星期日(或您正在寻找的任何一天),然后您以7天为单位进行增量,直到一个月结束。

$year="2023";
$month="05";
$start_date = $year."-".$month."-01";
$last_day =  date('Y-m-t',strtotime($start_date));
$total_week_days=array();
for ($i = 0; $i < ((strtotime($last_day) - strtotime($start_date)) / 86400); $i++)
{
if(date('l',strtotime($start_date) + ($i * 86400)) == "Sunday")
{
$total_week_days[]=date('Y-m-d',strtotime($start_date) + ($i * 86400));
}    
}
print_r($total_week_days);

这是上述函数的变体。在这里,您可以选择将显示一个月中的哪几天。例如,您想要显示2019年1月的所有星期二。

/*
 * @desc Funtion return array of dates. Array contains dates for custom
 *       days in week.
 * @input integer $year
 * @input integer $month - Month order number (1-12)
 * @input integer $dayOrderNumber - Monday is 1, Tuesday is 2 and Sunday is 7.
 * @return array $customDaysDates - Array of custom day's dates.
 */
function getCustomDaysDatesInMonth($year,$month,$dayOrderNumber){ 
    $date = "$year-$month-01";
    $firstDayInMonth = (integer) date('N',strtotime($date));
    $theFirstCustomDay = ( 7 - $firstDayInMonth + $dayOrderNumber)%7 + 1;
    $lastDayInMonth =  (integer) date('t',strtotime($date));
    $customDaysDates = [];
    for($i=$theFirstCustomDay; $i<=$lastDayInMonth; $i=$i+7 ){
        $customDaysDates[] = $i;
    }
    return  $customDaysDates;
}
$days = getCustomDaysDatesInMonth(2019,1, 2);
print_r($days);

输出应该是:

Array ( [0] => 1 [1] => 8 [2] => 15 [3] => 22 [4] => 29 ) 

这意味着2019年1月1日、8日、15日、22日和29日是星期二。