试试这段简单的代码:
function rangeSundays($year, $month_start, $month_end) {
$res = array();
for ($i = $month_start; $i <= $month_end; $i++) {
$dt = strtotime('last sunday of this month', strtotime("$year-$i-1"));
$res[] = date('Y-m-d', $dt);
}
return $res;
}
所以,以这种方式使用它
$date_array = rangeSundays(2011, 3, 10); // year, start month, end month
print_r($date_array);
输出
Array
(
[0] => 2011-03-27
[1] => 2011-04-24
[2] => 2011-05-29
[3] => 2011-06-26
[4] => 2011-07-31
[5] => 2011-08-28
[6] => 2011-09-25
[7] => 2011-10-30
)
此外,如果您的 php 配置 (php.ini) 中未设置默认时区,请在脚本开头添加类似这样的内容,以避免在 PHP 中引发警告。
date_default_timezone_set('UTC'); // or any other time zone
将此结果打印到屏幕使用
$date_array = rangeSundays(2011, 3, 10);
foreach($date_array as $x) {
echo "$x<br/>";
}
如果你想在不使用函数的情况下做到这一点
$year = 2011; // or which year you want
$month_start = 3; // for starting month; March in this case
$month_end = 10; // for ending month; October in this case
$res = array();
for ($i = $month_start; $i <= $month_end; $i++) {
$dt = strtotime('last sunday of this month', strtotime("$year-$i-1"));
$res[] = date('Y-m-d', $dt);
}
foreach($res as $sunday) {
echo "$sunday<br />";
}
输出
2011-03-27
2011-04-24
2011-05-29
2011-06-26
2011-07-31
2011-08-28
2011-09-25
2011-10-30
注意:在这种情况下,DST 不会影响日期。
您的代码看起来像不必要的复杂性:)