Home > OS >  Calculate n dates of next x days of the week
Calculate n dates of next x days of the week

Time:02-11

so I'm trying to build a function that allows me to calculate the dates of the next x days of the week, for example, I want 5 dates from now (02/08/2022), of Tuesday and Thursday, so the output should be:

 02/08/2022 - Tu
 02/10/2022 - Th
 02/15/2022 - Tu
 02/17/2022 - Th
 02/22/2022 - Tu

I'm not sure how to achieve that, since I want to be able to input various days of the week... Is there a way to do this? My current aproach is this one, but of couse, is not doing what I want, I kinda blocked right now, sorry if the answer is too obvious:

function getNextDates($start_date, $range_weeks, $how_many_dates, $days)
{

    $range = 'P' . ($range_weeks * 7) . 'D';
    $sd = new DateTimeImmutable($start_date);
    $nd = new DateTime($start_date);
    $dates_list = array();
    $dates_list[0] = array('day' => $sd->format('D'), 'date' => $sd->format('d-m-Y'));
    $ind = 1;
    $how_many_dates--;

    while ($how_many_dates > 0) {
        // This in case I want a n weeks space 
        $nd->add(new DateInterval($range));

        for ($i = 0; $i < count($days); $i  ) {
            if (($i   1) < count($days)) {
                if ($sd->modify($this->nextDay($days[$i])) < $sd->modify($this->nextDay($days[$i   1]))) {
                    $nextDate = $nd->modify($this->nextDay($days[$i]));
                    $dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
                    $how_many_dates--;
                    $ind  ;
                }
            } else {
                $nextDate = $nd->modify($this->nextDay($days[$i]));
                //   $sd = $nextDate;
                $dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
                $how_many_dates--;
                $ind  ;
            }
            if ($how_many_dates <= 0) break;
        }
    }

    return $dates_list;
}

Being:

$start_date: 02/08/2022
$range_weeks: 0 // Meaning every week
$how_many_dates: 5
$days: Tuesday, Thursday

I got:

02/08/2022
02/10/2022
02/17/2022
02/24/2022
03/03/2022

Sorry for my amateur code...

CodePudding user response:

Starting from the start date, a day is always added and it is checked whether it is the desired day of the week.

$start = "02/08/2022";
$number = 5;
$weekDays = ['Tue','Thu'];

$dates = [];
for($date = date_create($start); $number > 0; $date->modify(' 1 Day')){
  $day = $date->format('D');
  if(in_array($day,$weekDays)) {
    $dates[] = $date->format("d/m/Y");
    $number--;
  }
}

Result $dates

array (
  0 => "08/02/2022",
  1 => "10/02/2022",
  2 => "15/02/2022",
  3 => "17/02/2022",
  4 => "22/02/2022",
)
  • Related