我正在使用以下代码从给定的日期范围获取星期的开始(星期一)和结束的日期(星期日)。
function getWeekDates($date, $start_date, $end_date) {
$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$month = date('M', strtotime($date));
$from = date("Y-m-d", strtotime("{$year}-W{$week}")); //Returns the date of monday in week
if($from < $start_date) $from = $start_date;
$to = date("Y-m-d", strtotime("{$year}-W{$week}-7")); //Returns the date of sunday in week
if($to > $end_date) $to = $end_date;
$d = date('d', strtotime($from));
return ['week'=>$month."-".$d,'st'=>$from,'end'=>$to];
}
function getWeekDatesArr($start_date = null , $end_date = null) {
$arr = [];
for($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date. ' + 7 days'))) {
$list = getWeekDates($date, $start_date, $end_date);
$arr[$list['week']] = ['start'=>$list['st'],'end'=>$list['end']];
}
return $arr;
}
$start_date = '2019-10-14';
$end_date = '2020-01-05';
$dates = getWeekDatesArr($start_date, $end_date);
echo "<pre>";
print_r($dates);
在输出中,上一个开始日期和结束日期错误。明年不显示
[Dec-23] => Array
(
[start] => 2019-12-23
[end] => 2019-12-29
)
[Dec-14] => Array
(
[start] => 2019-10-14
[end] => 2019-01-06
)
答案 0 :(得分:1)
使用DateTime class更简单明了。
<?php
$start_date = '2019-10-14';
$end_date = '2020-01-05';
$date = date_create($start_date);
$end = date_create($end_date);
$dates = [];
while($date < $end){
$key = $date->format('M-d');
$dates[$key] = [
'start' => $date->format('Y-m-d'),
'end' => $date->modify('next Sunday')->format('Y-m-d')
];
$date->modify('next Monday');
}
//test output
echo "<pre>";
var_dump($dates);
注意: 键为“ M-d”会引起问题。几年来,密钥不再唯一。最好也将年份包括在密钥中。