How to get all fridays within date range by carbon
Asked Answered
S

2

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?

Sinuosity answered 30/1, 2017 at 14:13 Comment(2)
Not a really Carbon, moreover, sadly not even fridays, but you might found it useful: #7062302Tybie
Anyway looking through carbon.nesbot.com/docs I don't think so there is a single function, like yours :)Tybie
F
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');
}
Fissirostral answered 30/1, 2017 at 14:43 Comment(1)
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")Sceptre
G
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');
}
Gulgee answered 4/6, 2020 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.