I am creating some dates with Carbon in PHP, but I seem to be doing something wrong.
This here is my code:
$start = Carbon::create(2015, rand(6,7), rand(1,30), 0);
$end = $start->addWeeks(3);
echo "start time: " . $start;
echo "<br />";
echo "end time: " . $end;
And the output of the above is two exact same dates, e.g.:
start time: 2015-07-01 00:00:00
end time: 2015-07-01 00:00:00
I reffered to the docs, which can be found here: http://carbon.nesbot.com/docs/#api-addsub. Does anybody know what am I doing wrong?
I haven't worked with Carbon yet but I'd say those Carbon object are mutable. Also most functions seem to return $this
for method chaining (aka fluent interface).
Thus, when doing $end = $start->addWeeks(3);
your $end
is actually the same object as $start
. (just an intelligent guess)
To avoid this try to either clone
the object before manipulation (if possible) or create another one.
Version 1
$start = Carbon::create(2015, rand(6,7), rand(1,30), 0);
$end = clone $start;
$start->addWeeks(3);
Version 2
$start = Carbon::create(2015, rand(6,7), rand(1,30), 0);
$end = Carbon::create(2015, rand(6,7), rand(1,30), 0);
$start->addWeeks(3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With