I want to find out next X dates based on weekly repetition. For example, today’s date is 8th May, 2023, i want to find out next 4 dates for Monday & Friday (i.e. Weekly on Monday, Friday, 4 times)
So expected result will be:
8th May, 2023
12th May, 2023
15th May, 2023
19th May, 2023
$appointment_start_date = "2023-05-08";
$all_appointments[] = [
'appointment_date' => $appointment_start_date
];
$post['weekly_day'] = ["Monday", "Friday"];
$recurrence_end_after = 4;
// Create a new DateTime object
$date = new DateTime($appointment_start_date);
for ($i=1; $i<=$recurrence_end_after; $i++) {
foreach ($post['weekly_day'] as $weekly_day) {
if ($i > $recurrence_end_after) {
break;
}
// Modify the date it contains
$date->modify('next ' . $weekly_day);
// Output
$appointment_start_date = $date->format('Y-m-d');
$all_appointments[] = [
'appointment_date' => $appointment_start_date
];
$i++;
}
}
But this snippet doesn’t return the expected result. It just return
2023-05-08, 2023-05-15, 2023-05-19, 2023-05-22 so it skips the Friday date (i.e. 12th May, 2023)
Few more examples
Input: 1st June, 2023.
recurrence_end_after: 6.
weekly_day: Monday, Friday.
Expected output:
- 1st June, 2023
- 2nd June, 2023
- 5th JUne, 2023
- 9th June, 2023
- 12th June, 2023
- 19th June, 2023
Input: 10th May, 2023.
recurrence_end_after: 4.
weekly_day: Saturday, Sunday
Expected Output:
- 10th May, 2023
- 13th May, 2023
- 14th May, 2023
- 19th May, 2023
2
Answers
When I test this code i get 2023-05-15, 2023-05-19, 2023-05-22
In your foreach you’re first looking for the first monday after 2023-05-08 and that’s 2023-05-15, next time you’re looking for the next friday and then the next monday.
If you want to get 2023-05-12 you’ll first need to determine if you want the foreach to start with looking at the next monday or to start with the next friday.
There’s also a problem with your for loop: you’ld better change it to
Because now it add 1 to $i when you don’t want it to.