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?
$now = Carbon\Carbon::now(); $month = $now->format('m'); Assuming the current month was January, you would receive '01' from that format call. As an aside, if that's all you're using Carbon for in that class, you could just use the default PHP date() method if you feel like using less dependencies.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With