我试图在laravel的select字段中获取特定日期之前和之后的7个日期的日期列表。 例如,如果特定日期是“ 2019-07-18”,我想在选择字段中填充日期列表,从“ 2019-07-11”到“ 2019-07-25”。 谁能为我提供控制器的代码片段来实现这一目标。
答案 0 :(得分:3)
function getAgoDays($specDay, $days, $format = 'Y-m-d') {
$d = date('d', strtotime($specDay));
$m = date('m', strtotime($specDay));
$y = date('Y', strtotime($specDay));
$dateArray = array();
for($i=1; $i<=$days; $i++) {
$dateArray[] = '"' . date($format, mktime(0,0,0,$m,($d-$i),$y)) . '"';
}
return array_reverse($dateArray);
}
function getBeforeDays($specDay, $days, $format = 'Y-m-d') {
$d = date('d', strtotime($specDay));
$m = date('m', strtotime($specDay));
$y = date('Y', strtotime($specDay));
$dateArray = array();
for($i=1; $i<=$days; $i++) {
$dateArray[] = '"' . date($format, mktime(0,0,0,$m,($d+$i),$y)) . '"';
}
return $dateArray;
}
使用
$agoDays = getAgoDays('2019-07-18', 7, 'Y-m-d');
echo '<pre>';
print_r($agoDays);
echo '</pre>';
$agoDays = getBeforeDays('2019-07-18', 7, 'Y-m-d');
echo '<pre>';
print_r($agoDays);
echo '</pre>';
答案 1 :(得分:2)
您可以使用carbon period:
$givenDate = "2019-07-18";
$dateMinusOneWeek = Carbon::parse($givenDate)->subWeek()->format('Y-m-d');
$datePlusOneWeek = Carbon::parse($givenDate)->addWeek()->format('Y-m-d');
$period = CarbonPeriod::create(dateMinusOneWeek , datePlusOneWeek);
//You can iterate over the period
foreach ($period as $date) {
echo $date->format('Y-m-d');
}
//Or convert the period to an array of dates
$dates = $period->toArray();
希望有帮助。