/**
* @param string $from начало периода
* @param string $to конец периода
*
* @return array
*/
function getWeekPeriod($from, $to)
{
$weeks = [];
$from = strtotime($from);
$to = strtotime($to);
while ($from < $to) {
// echo "from:\t", date('d.m.Y', $from), RN;
// номер дня недели начала периода
$fromDay = date("N", $from);
// echo "fromDay:\t", $fromDay, RN;
// если не ВС
if ($fromDay < 7) {
// кол-во дней до ВС
$daysToSun = 7 - $fromDay;
// echo "daysToSun:\t", $daysToSun, RN;
// конец недельного периода
$end = strtotime("+ $daysToSun day", $from);
// если попадаем на след. месяц, то делаем новые вычисления
if (date("n", $from) != date("n", $end)) {
$end = strtotime("last day of this month", $from);
}
$weeks[] = [date('d.m.Y', $from), date('d.m.Y', $end)];
$from = $end;
} else {
$weeks[] = [date('d.m.Y', $from), date('d.m.Y', $from)];
}
// echo "end:\t", date('d.m.Y', $from), RN, RN;
$from = strtotime("+1 day", $from);
}
return $weeks;
}
$start = new DateTime('01.08.2014');
$end = new DateTime('30.08.2015 23:59');
$interval = new DateInterval('P1D');
$dateRange = new DatePeriod($start, $interval, $end);
$weekNumber = 1;
$weeks = array();
foreach ($dateRange as $date) {
$weeks[$weekNumber][] = $date->format('Y-m-d');
if ($date->format('w') == 0) {
$weekNumber++;
}
}
echo '<pre>';
print_r($weeks);
echo '</pre>';
function getWeekPeriods(Carbon $from, Carbon $to)
{
$weeks = [];
$currentDate = $from;
while ($to->greaterThan($currentDate)) {
$currentDate = $currentDate->startOfDay();
$endOfTwoWeeksRange = (clone $currentDate)->addWeek()->endOfWeek();
if ($endOfTwoWeeksRange->greaterThan($to)) {
$weeks[] = ['start' => $currentDate->isoFormat('DD.MM.Y HH:mm:ss'), 'end' => $to->isoFormat('DD.MM.Y HH:mm:ss')];
break;
}
$weeks[] = ['start' => $currentDate->isoFormat('DD.MM.Y HH:mm:ss'), 'end' => $endOfTwoWeeksRange->isoFormat('DD.MM.Y HH:mm:ss')];
$currentDate = $endOfTwoWeeksRange->addDay();
}
return $weeks;
}
{
"date_from":"2023-01-03",
"date_to":"2023-02-28"
}
[
{
"start": "03.01.2023 00:00:00",
"end": "15.01.2023 23:59:59"
},
{
"start": "16.01.2023 00:00:00",
"end": "29.01.2023 23:59:59"
},
{
"start": "30.01.2023 00:00:00",
"end": "12.02.2023 23:59:59"
},
{
"start": "13.02.2023 00:00:00",
"end": "26.02.2023 23:59:59"
},
{
"start": "27.02.2023 00:00:00",
"end": "28.02.2023 10:00:00"
}
]