Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

Carbon : How to Get weeks date in a given date period

Hello ,

Let's imagine I have this start/end date [01-01-2019 to 01-02-2019] I would like an array with all weeks and their start/end date :

$weeks:
        [
            "0"=>["from"=>"01-01-2019", "07-01-2019"],
            "1"=>["from"=>"08-01-2019", "15-01-2019"],
                ....
        ]

Is it possible to make it with Carbon?

0 likes
1 reply
Sti3bas's avatar

Something like that:

public function weeksBetweenTwoDates($start, $end)
{
    $weeks = [];

    while ($start->weekOfYear !== $end->weekOfYear) {
        $weeks[] = [
            'from' => $start->startOfWeek()->format('Y-m-d'),
            'to' => $start->endOfWeek()->format('Y-m-d')
        ];

        $start->addWeek(1);
    }

    return $weeks;
}
$this->weeksBetweenTwoDates(Carbon::now(), Carbon::now()->addDays(16));

Results:

[
  0 => [
    "from" => "2019-09-16",
    "to" => "2019-09-22"
  ],
  1 => [
    "from" => "2019-09-23",
    "to" => "2019-09-29"
  ]
]
3 likes

Please or to participate in this conversation.