I'm using this function to get all Fridays between two dates:
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');
result :
array:4 [▼
0 => "2017-01-06"
1 => "2017-01-13"
2 => "2017-01-20"
3 => "2017-01-27"
]
Is there any function in carbon
like above?
You can use all the power of Carbon like this:
$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');
}
Slight modification to Alexey Mezenin's answer to include the current day if it is a Friday.
$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');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.