Reputation: 404
So I'm trying to add a year based on the user registration date, and I need to compare the date, but it's updating the original date from registration date.
$registered_at = Carbon::parse('2020-10-17 03:05:03');
$final_date = $registered_at->addYear();
echo $registered_at.'<br>';
echo $final_date;
result is the same, I want to preserved the registered_at
date to 2020-10-17 03:05:03
registered_at : 2021-10-17 03:05:03
final date: 2021-10-17 03:05:03
I am expecting 2020-10-17 03:05:03
registered_at : 2020-10-17 03:05:03
final date: 2021-10-17 03:05:03
Upvotes: 0
Views: 949
Reputation: 5131
When you don't want your instances to be mutated on add/sub/set, use CarbonImmutable
:
$registered_at = CarbonImmutable::parse('2020-10-17 03:05:03');
$final_date = $registered_at->addYear();
echo $registered_at.'<br>';
echo $final_date;
Else use ->copy()
to create a new instance.
Upvotes: 1
Reputation: 34848
Add addYear()
value :
$registered_at = Carbon::parse('2020-10-17 03:05:03');
$final_date = $registered_at->addYear(1); // added 1 year
echo $registered_at; // 2020-10-17 03:05:03
echo $final_date; // 2021-10-17 03:05:03
Upvotes: 1
Reputation: 703
In Carbon, when you call any method, it will change the instance.
In your case, you should use the copy()
method to make a new instance before call method.
Ex:
$registered_at = Carbon::parse('2020-10-17 03:05:03');
$final_date = $registered_at->copy()->addYear();
echo $registered_at.'<br>';
echo $final_date;
Upvotes: 3
Reputation: 8138
You need to copy the instance first like this:
$date_parse = Carbon::parse('2020-10-17 03:05:03');
$registered_at = $date_parse->copy();;
$final_date = $date_parse->addYear();
echo $registered_at.'<br>';
echo $final_date;
Upvotes: 1