I have function of return weeks in year:
function getWeek(){
$today = \Carbon\Carbon::today();
$date = $today->copy()->firstOfYear()->startOfDay();
$eom = $today->copy()->endOfYear()->startOfDay();
$dates = [];
for($i = 1; $date->lte($eom); $i ){
$startDate = $date->copy();
while($date->dayOfWeek != \Carbon\Carbon::SUNDAY && $date->lte($eom)){
$date->addDay();
}
$dates['w'.$i] = $startDate->format('d/m/Y') . ' - ' . $date->format('d/m/Y');
$date->addDay();
}
return $dates;
}
And the function return 53 weeks in year 2022 but in 2022 is 52 weeks. This is a result of return $dates
How to change the function to return first position to return full dates of week (27/12/2021 - 02/01/2022) and the same at the last position in year
CodePudding user response:
I think you are mistaken.
w1->w53 = 52 weeks
CodePudding user response:
This solution always shows the complete weeks. Uses the ISO 8601 week number. Only DateTime is required. The year was added for the key so that they are always unique.
$year = date_create('today')->format('Y');
//remove comment next line for test's
//$year = 2001;
$dtStart = date_create('2 jan '.$year)->modify('last Monday');
$dtEnd = date_create('last monday of Dec '.$year);
for($weeks = [];$dtStart <= $dtEnd;$dtStart->modify(' 1 week')){
$key = $dtStart->format('W-Y');
$from = $dtStart->format('d/m/Y');
$to = (clone $dtStart)->modify(' 6 Days')->format('d/m/Y');
$weeks[$key] = $from.' - '.$to;
}
var_export($weeks);
Since carbon is not required, you can also test it here.