Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all fridays within date range by carbon

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?

like image 369
S.M_Emamian Avatar asked Jan 30 '17 14:01

S.M_Emamian


People also ask

How do you find the current month in Carbon?

$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.


2 Answers

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');
}
like image 149
Alexey Mezenin Avatar answered Nov 09 '22 09:11

Alexey Mezenin


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');
}
like image 31
Joel Brubaker Avatar answered Nov 09 '22 10:11

Joel Brubaker