我使用此功能获取两个日期之间的所有星期五:
EXEC proc_GetQuarterlyEmailId ?, ?, ?, ?
结果:
public function getFridaysInRange($dateFromString, $dateToString)
{
$dateFrom = new \DateTime($dateFromString);
$dateTo = new \DateTime($dateToString);
$dates = [];
if ($dateFrom > $dateTo) {
return $dates;
}
if (1 != $dateFrom->format('N')) {
$dateFrom->modify('next friday');
}
while ($dateFrom <= $dateTo) {
$dates[] = $dateFrom->format('Y-m-d');
$dateFrom->modify('+1 week');
}
return $dates;
}
$this->getFridaysInRange('2017-01-01','2017-01-30');
上面的array:4 [▼
0 => "2017-01-06"
1 => "2017-01-13"
2 => "2017-01-20"
3 => "2017-01-27"
]
中是否有任何功能?
答案 0 :(得分:5)
你可以像这样使用Carbon的所有力量:
$fridays = [];
$startDate = Carbon::parse($fromDate)->next(Carbon::FRIDAY); // Get the first friday.
$endDate = Carbon::parse($toDate);
for ($date = $startDate; $date->lte($endDate); $date->addWeek()) {
$fridays[] = $date->format('Y-m-d');
}
答案 1 :(得分:1)
对Alexey Mezenin的答案进行了轻微修改,以包括当前日期(如果是星期五)。
$fridays = [];
$startDate = Carbon::parse($fromDate)->modify('this friday'); // Get the first friday. If $fromDate is a friday, it will include $fromDate as a friday
$endDate = Carbon::parse($toDate);
for ($date = $startDate; $date->lte($endDate); $date->addWeek()) {
$fridays[] = $date->format('Y-m-d');
}