Get all recurring dates between 2 dates

April 26th, 2023

How to get all dates for a recurring event?

If an event is recurring monthly, get all the dates between the start and end date:

  1. get a number of repeats (difference in months between the end date and start date)

  2. loop as many times as the calculated number of repeats

  3. add month to the previous value in an array

  4. you have to clone() the previous value before addMonth because it is a Carbon object which is mutable. If you don't clone, it will also change the previous original value -> more on Carbon Mutable.

1$start_date = new Carbon('2022-11-09');
2$end_date = new Carbon('2023-01-10');
3 
4// get number of repeats, if event is recurring monthly
5$number_of_repeats = $end_date->diffInMonths($start_date); // 2
6 
7$recurring_dates = [$start_date];
8 
9// addMonth to previous value in array ($recurring_dates[$i])
10for($i=0; $i<$number_of_repeats; $i++){
11 $recurring_dates[] = $recurring_dates[$i]->clone()->addMonth(1);
12}
13 
14dd($recurring_dates);
15// 2022-11-09, 2022-12-09, 2023-01-09 Carbon objects

Related Posts