Answer the question
In order to leave comments, you need to log in
PHP. Is there a solution that will split the date range into week periods?
you need to come up with an algorithm that will break the date interval into weekly periods. A week is the interval from Mon to Sun or the current day to Sun (for example, if the first day of the month falls on a day other than Mon) or Mon to the current day (if the end of the month falls on a day other than Sun).
Example:
input data 08/01/2014 - 08/30/2015
output:
08/01/2014 - 08/03/2014
08/04/2014 - 08/10/2014
08/11/2014 - 08/17/2014
08/18/2014 -
08/25/2014 08/25/2014 - 08/25/2014 08/25/2014 - 08/31/2014
01.09 .2014 - 07.09.2014
...
29.09.2014 - 30.09.2014
01.10.2014 - 05.10.2014
06.10.2014 - 12.10.2014
...
Answer the question
In order to leave comments, you need to log in
Thanks to all. Here is my solution:
/**
* @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>';
Not that it’s a ready-made solution, but there is a Carbon library for working with dates, there are methods for determining the end of the week and adding a week, and then it seems trivial - you found the first day off and add weeks from it until you exhaust the entire period.
1) mktime function - returns unix timestamp for a given date (well, or, alternatively, strtotime function)
2) pass the result of one of the above two functions to date('N', strtotime('08/01/2014'));
The result is a number from 1 to 7, where 1 is Monday and 7 is Sunday. Alternatively, you can date('w'), where 0 is Sunday, 6 is Saturday.
3) and then implement it somehow through a cycle or in some other way.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question