Reputation: 415
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?
Upvotes: 5
Views: 10914
Reputation: 692
because you'r not parsing date ($start) in carbon parse method,
$start = Carbon::create(2015, rand(6,7), rand(1,30), 0);
$end = Carbon::parse($start)->addWeeks(3);
i have not tested your code but hope so it work.
Upvotes: 0
Reputation: 324
Carbon dates are mutable. Try this:
$rand_date = Carbon::create(2015, rand(6,7), rand(1,30), 0);
echo "start time: " . $rand_date->format('Y-m-d');
echo "<br />";
echo "end time: " . $rand_date->addWeeks(3)->format('Y-m-d');
Upvotes: 1
Reputation: 3161
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);
Upvotes: 8
Reputation: 2449
$end takes the same value as $start after the addition and it looks like it has not changed. But it has:
>>> use Carbon\Carbon;
=> false
>>> $start = Carbon::create(2015, rand(6,7), rand(1,30), 0);
=> Carbon\Carbon {#766
+"date": "2015-07-16 00:00:00",
+"timezone_type": 3,
+"timezone": "Asia/Bangkok",
}
>>> $end = $start->addWeeks(3);
=> Carbon\Carbon {#766
+"date": "2015-08-06 00:00:00",
+"timezone_type": 3,
+"timezone": "Asia/Bangkok",
}
>>> $end
=> Carbon\Carbon {#766
+"date": "2015-08-06 00:00:00",
+"timezone_type": 3,
+"timezone": "Asia/Bangkok",
}
>>> $start
=> Carbon\Carbon {#766
+"date": "2015-08-06 00:00:00",
+"timezone_type": 3,
+"timezone": "Asia/Bangkok",
}
Upvotes: 1