2

I have a start date and end date.
I'm trying to get all the Tuesdays and Wednesdays of every two weeks.

Example:

2017-05-23 (tu)
2017-05-24 (we)

2017-06-06 (tu)
2017-06-07 (we)
...

What I'm trying to do in PHP:

$start = new FrozenTime('2017-05-23'); // Date is in this format 'cause I'll save into DB  
$endOfYear = $start->endOfYear();  

$perWeek = new \DateInterval('P14D'); // I want every 2 weeks

$periodPerWeek = new \DatePeriod($start, $perWeek, $endOfYear);  

$days = ['2', '3']; // Tuesday and Wednesday  

foreach ($periodPerWeek as $value) {
   if (in_array($value->format('N'), $days)) {
        $test[] = [
            'start' => $value
        ];    
   }
}  

The results:

"start": "2017-05-23",  
"start": "2017-06-06",  
"start": "2017-06-20",  

It's getting only one date in array. I need to get the Wednesday's too! How can I do it?

IMPORTANT:
The start date will not be always Tuesday. The user can choose the week days that he wants.

Ex: The user can choose every SU, WE and FR in every two weeks.

// start date example: 2017-05-20 (saturday)
// output should be like:
2017-05-22 (SU)  
2017-05-24 (WE)  
2017-05-26 (FR)  
2017-06-05 (SU)  
2017-06-07 (WE)  
2017-06-09 (FR)  
...
Community
  • 1
  • 1
Victor
  • 724
  • 3
  • 12
  • 32

1 Answers1

1

One way to do it

/**
 * @param \DateTime $start 
 * @param \DateTime $end 
 * @param array $days i.e. ['tue', 'wed', 'sat']
 * 
 * @return array
 */

function every_two_weeks($start, $end, $days) 
{
    $dates = [];

    $mon = new DateTime('mon this week '.$start->format('Y-m-d'));

    while ($mon <= $end) {
        $of = 'this week '.$mon->format('Y-m-d');

        foreach ($days as $day) {
            $date = new DateTime("$day $of");

            if ($date < $start) {
                continue;
            }

            if ($date > $end) {
                break 2;
            }

            $dates[] = $date;
        }

        $mon->add(new DateInterval('P2W'));
    } 

    return $dates;
}

Usage:

$start = new DateTime('2017-05-23');
$end = new DateTime('2017-06-21');

$dates = every_two_weeks($start, $end, ['tue', 'wed', 'sat']);

Output:

2017-05-23 Tue
2017-05-24 Wed
2017-05-27 Sat
2017-06-06 Tue
2017-06-07 Wed
2017-06-10 Sat
2017-06-20 Tue
2017-06-21 Wed

3v4l demo

peterm
  • 91,357
  • 15
  • 148
  • 157