renanrfranca
renanrfranca

Reputation: 71

Can't get monthy CarbonPeriod to behave as desired

In the project I'm working on I have a daily command that basically checks the date of the last record in the database and tries to fetch data from an API from the day after and then each month after that (the data is published monthly).

Basically, the last record's date is 2019-08-30. I'm mocking as if I were running the task on 2019-09-01 with

$test = Carbon::create(2019,9,1,4);
Carbon::setTestNow($test);

I then create a monthly period between the next day of the last record's date and the last day of the current month like so:

$period = CarbonPeriod::create($last_record_date->addDay(), '1 month', $last_day_of_current_month);

Successfully generating a period with start_date = 2019-08-31 and end_date = 2019-09-30. Which I use in a simple foreach.

What I expected to happen is that it runs twice, once for August and once for September, but it's running only once for the start date. It's probably adding a month and going past the end date, but I don't know how to force the behaviour I'm looking for.

TL;DR:

$period = CarbonPeriod::create('2019-08-31', '1 month', '2019-09-30');

foreach ($period as $dt) {
    echo $dt->format("Y-m") . "<br>\n";
}

This will print just 2019-08, while I expect 2019-08 and 2019-09. What's the best way to achieve that?

Upvotes: 0

Views: 1225

Answers (2)

Shagun
Shagun

Reputation: 21

Solution :- You can store actual date in $actual_day and current date for occurring monthly in $current_day. Put a check on comparing both dates, if not matched then make it on the same day it will skip 30,31 case in case of February month.

 $current_date = $current_date->addMonths(1);
if($current_date->day != $actual_day){
    $date = Carbon::parse($date->year."-".$date->month."-".$actual_day);
 }

Upvotes: 2

Calum Halpin
Calum Halpin

Reputation: 2095

Your start date is 2019-08-31. Adding a month takes you to 2019-09-31. 2019-09-31 doesn't exist so instead you get 2019-10-01, which is after your end date. To avoid this I'd suggest you use a more regular interval such as 30 days.

Otherwise you're going to have to rigorously define what you mean by "a month later". If the start date is 31st Jan is the next date 28th February? Is the month after 28th or 31st March? How do leap years affect things?

Upvotes: 1

Related Questions