0

I have a date range ($startDate, $endDate). Based on the range that is given I need to loop through each month and run a specific job.

Currently I am doing this as such:

    //Get startOf and endOf to cover entire month of range.
    $currentDate = Carbon::parse($startDate)->startOfMonth();
    $endDate = Carbon::parse($endDate)->endOfMonth();

    //Number of weeks helps with the for loop
    $numberOfMonths = $currentDate->diffInMonths($endDate);

    for ($x = 0; $x <= $numberOfMonths; $x++)
    {
        //something here

        $currentDate = $currentDate->addMonths(1);
    }

This is done with carbon and php. The problem with the current method is that diffInMonths apparently simply divides by 30 and some how skips February as it only has 28 days.

I need some sort of loop by each month. So for example if my date range was 2018-01-15 and 2018-04-25, it should loop through four times, 1/2/3/4 and stop. Currently it is going 1/3/4 and stop.

Is there some simple work around for this, that I can loop through the months within a date range?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Abhishek Shah
  • 145
  • 2
  • 11
  • Instead of using `addMonths()`, I'd treat the year and month as plain integers and increment increment them accordingly. Years will always be consecutive, and there will always be 12 months. If you need an actual Carbon instance within your for loop, construct it from the year/month each time. – John Ellmore Apr 27 '18 at 17:39
  • I can't use year because i am not sure if the date range covers an entire year. for example if the date range covers 2 weeks, then i have to loop through one month. My loop needs by month in which i run the code through the first and last days of that month. This code kind of works, but there is a bug regarding the month of Feb. no matter how i go about it, it tends to skip, and I belive its due to diffInMonths() function – Abhishek Shah Apr 27 '18 at 17:47

0 Answers0