Home > Blockchain >  PHP get date between a date range and separate by week
PHP get date between a date range and separate by week

Time:09-12

How can I create a function that can return accurate start and end date within date range of given date that separate by week.

For example, a date range is given,

$startDate = '2022-08-05';
$endDate = '2022-08-16';

(2022-08-01 is the first day of the week but I want the data return start from the date that user given so do the end date)

So the output should be like this:

2022-08-05 to 2022-08-07 2022-08-08 to 2022-08-14 2022-08-15 to 2022-08-16
data data data

My problem is function I found cannot get data start from that date that user given but start from the first day of week and I have no idea how to modify it or create a new function. Any help is appreciate.

 function rangeWeek ($datestr) {
   date_default_timezone_set (date_default_timezone_get());
   $dt = strtotime ($datestr);
   return array (
     "start" => date ('N', $dt) == 1 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('last monday', $dt)),
     "end" => date('N', $dt) == 7 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('next sunday', $dt))
   );
 }

If I set the start date to '2022-08-05' then the output will be start from the first day of the week, how to let it start from '2022-08-05'?

print_r (rangeWeek('2022-08-05'));//output = Array ( [start] => 2022-08-01 [end] => 2022-08-07 ) 

CodePudding user response:

You can iterate from start to end date and check the week for each day. So you know the week begin and end.

Example

function rangeWeek(string $start, string $end): array
{
    $start     = new DateTime($start);
    $end       = new DateTime($end);
    $interval  = new DateInterval('P1D');
    $period    = new DatePeriod($start, $interval, $end);
    $weeks     = [];
    $oldWeek   = null;
    $weekStart = null;
    foreach ($period as $date) {
        $week = $date->format('W');
        if ($week !== $oldWeek) {
            if (null === $weekStart) {
                $oldWeek   = $week;
                $weekStart = $date->format('Y-m-d');
            } else {
                $weeks[]   = ['start' => $weekStart, 'end' => $date->format('Y-m-d'), 'week' => $week];
                $weekStart = null;
            }
            continue;
        }
    }
    
    $weeks[] = ['start' => $weekStart, 'end' => $end->format('Y-m-d'), 'week' => $week];

    return $weeks;
}

$startDate = '2022-08-05';
$endDate   = '2022-08-20';
$weeks     = rangeWeek($startDate, $endDate);
print_r($weeks);

Output

Array
(
    [0] => Array
        (
            [start] => 2022-08-05
            [end] => 2022-08-08
            [week] => 32
        )

    [1] => Array
        (
            [start] => 2022-08-09
            [end] => 2022-08-15
            [week] => 33
        )

    [2] => Array
        (
            [start] => 2022-08-16
            [end] => 2022-08-20
            [week] => 33
        )

)
  •  Tags:  
  • php
  • Related