Search code examples
phplaraveldatephp-carbon

Change call method addMonth() to addMonthsWithOverflow() carbon


I update all my project built in Laravel.

In many part of this project, I have this code:

$FI->copy()->addMonth(3)->subDay();

but when I pass phpStan it returns

Method Carbon\Carbon::addMonth() invoked with 1 parameter, 0
         required.

Now I have to change to this method

$FI->copy()->addMonthsWithOverflow(3)->subDay();

But I don´t know, if this code is same as the previous code. I´m building script to try check, if both dates are same:

$period = CarbonPeriod::create('2023-12-31T00:00:00Z', '2024-05-31T00:00:00Z');

    // Iterate over the period
    $dates = array();
    foreach ($period as $date) {
        $date->format('Y-m-d\TH:i:s\Z');
        $final_date = $date->copy()->addMonth(3)->subDay();
        array_push($dates, $final_date);
    }

    foreach ($dates as $key => $value){
        echo "key ".$key." value: ".$value."<br>";
    }

    echo "<br>";

    $dates2 = array();
    foreach ($period as $date) {
        $date->format('Y-m-d\TH:i:s\Z');
        $final_date = $date->copy()->addMonthsWithOverflow(3)->subDay();
        array_push($dates2, $final_date);
    }

    foreach ($dates as $key => $value){
        echo "key2 ".$key." value2: ".$value."<br>";
    }

I can show that both dates are same, but I need to be sure that this new method is correct.


Solution

  • In Carbon there is a difference between addMonth() and addMonths(). addMonth() is a shorthand for addMonths(1), if you want to invoke the method with a parameter, as you are doing right now, it should be addMonths(3) instead of addMonth().