Reputation: 55
I'm using Laravel for one of my project. Everything is just fine, but I can't solve a strange error.
Now when I do this in actual code, I see same start and end date generated according to plan end.
$start = Carbon::parse($client->plan_end) ?: Carbon::now();
$end = $start->addYears($request->planDetails['duration']);
return response([
'start' => $start,
'end' => $end,
]);
This is plan_end timestamp in database -- 2022-05-09 09:15:19
This is response I receive.
{
"start" : "2024-05-09T07:15:19.000000Z",
"end" : "2024-05-09T07:15:19.000000Z"
}
Upvotes: 4
Views: 545
Reputation: 5131
Using ->copy()
is fine, but using CarbonImmutable
as default is likely better as it will avoid similar pain to happen again:
$start = CarbonImmutable::parse($client->plan_end) ?: CarbonImmutable::now();
$end = $start->addYears($request->planDetails['duration']);
return response([
'start' => $start,
'end' => $end,
]);
Upvotes: 1
Reputation: 257
So carbon is mutable which means that when you do ->addYears()
it will alter the original start date time. You can use the ->copy()
function before adding the years so it would look like this.
$end = $start->copy()->addYears($request->planDetails['duration']);
Upvotes: 5