'Calculate n dates of next x days of the week
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...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
