phpdatephp-carbon

Carbon add method


Certainly something trivial, but I'm stuck!

I have a start date initialized like this:

$startDate = Carbon::createFromFormat('Y-m-d H:i', '2024-02-01 08:00');

I add days to this date to get an end date:

$qtyDays = 25;
$endDate = $startDate->addDays($qtyDays);

What I don't understand is that the end date is calculated correctly. But the start date contains the end date.

How not to touch the start date ? Even though I read the Carbon doc, I don't understand what's going on.


Solution

  • Actually it is not related to Carbon itself, as Carbon is just a wrapper for the PHP DateTime class, and as long as the PHP has DateTime & DateTimeImmutable, Carbon also do has the wrapper for both.:

    This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called.

    So you can use the CarbonImmutable like:

    $startDate = CarbonImmutable::createFromFormat('Y-m-d H:i', '2024-02-01 08:00');
    $qtyDays = 25;
    $endDate = $startDate->addDays($qtyDays);