Skip to content

Instantly share code, notes, and snippets.

@nmfzone
Last active January 19, 2021 00:33
Show Gist options
  • Save nmfzone/391257870970c7b0702ccf76422b082c to your computer and use it in GitHub Desktop.
Save nmfzone/391257870970c7b0702ccf76422b082c to your computer and use it in GitHub Desktop.
Get Start Date and End Date every weeks in a month with Carbon
<?php
public function getWeeks(int $month, int $year = null): array {
$year = is_null($year) ? Carbon::now()->year : $year;
$date = Carbon::createFromFormat('Y-m', $year . '-' . $month)
->firstOfMonth();
$oDate = $date->copy();
$data = [];
while($date->month == $month) {
$start = $date->copy()->startOfWeek();
$end = $date->copy()->endOfWeek();
$data[$date->weekOfMonth-1]['start'] = $start->month == $month
? $start->format('Y-m-d')
: $oDate->format('Y-m-d');
$data[$date->weekOfMonth-1]['end'] = $end->month == $month
? $end->format('Y-m-d')
: $oDate->endOfMonth()->format('Y-m-d');
$date->addWeek();
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment