5

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?

Machavity
  • 30,841
  • 27
  • 92
  • 100
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • Not a really Carbon, moreover, sadly not even fridays, but you might found it useful: http://stackoverflow.com/questions/7061802/php-function-for-get-all-mondays-within-date-range – hradecek Jan 30 '17 at 14:31
  • Anyway looking through http://carbon.nesbot.com/docs/ I don't think so there is a single function, like yours :) – hradecek Jan 30 '17 at 14:41

2 Answers2

10

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');
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • 2
    Just in case anyone decides to use this code. ->next(Carbon::FRIDAY) will not get the "first" friday if the start date falls on a friday. next() will ignore the first day and go to the "next" day. I'm not sure what the best way to get the "first" friday would be, but I used something like: ->sub("1 Day")->next("Friday") – Kyle Aug 24 '19 at 08:31
3

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');
}