Jonjie
2 months ago
206
1
Laravel

How to get all weeks in a month using Carbon

Posted 2 months ago by Jonjie

I want to return all weeks in a current month using carbon. So each week I want to return 2 dates. Please see my code below:

$dt = Carbon::now(); //or initialize it any other way
        
Carbon::setWeekStartsAt(Carbon::MONDAY);
Carbon::setWeekEndsAt(Carbon::SUNDAY);

$weeks += [
    'w1' => $dt->subDays($dt->dayOfWeek - 4)->format('Y-m-d H:i:s') . ' - ' . $dt->subDays($dt->dayOfWeek - 7)->format('Y-m-d H:i:s')
]; 

$weeks += [
    'w2' => $dt->subDays($dt->dayOfWeek - 3)->format('Y-m-d H:i:s') . ' - ' . $dt->subDays($dt->dayOfWeek - 7)->format('Y-m-d H:i:s')
]; 
$weeks += [
    'w3' => $dt->subDays($dt->dayOfWeek - 1)->format('Y-m-d H:i:s') . ' - ' . $dt->subDays($dt->dayOfWeek - 7)->format('Y-m-d H:i:s')
]; 

$weeks += [
    'w4' => $dt->subDays($dt->dayOfWeek - 1)->format('Y-m-d H:i:s') . ' - ' . $dt->subDays($dt->dayOfWeek - 7)->format('Y-m-d H:i:s')
];

return $weeks;

That code returns this:

"data": {
   "w1": "2020-08-27 06:45:01 - 2020-08-30 06:45:01",
   "w2": "2020-09-02 06:45:01 - 2020-09-06 06:45:01",
   "w3": "2020-09-07 06:45:01 - 2020-09-13 06:45:01",
   "w4": "2020-09-14 06:45:01 - 2020-09-20 06:45:01"
}

What output I want

"data": {
   "w1": "2020-08-03 06:09:06 - 2020-08-09 06:09:06",
   "w2": "2020-08-10 06:09:06 - 2020-08-16 06:09:06",
   "w3": "2020-08-17 06:09:06 - 2020-08-23 06:09:06",
   "w4": "2020-08-24 06:09:06 - 2020-08-30 06:09:06",
}

Please sign in or create an account to participate in this conversation.