$date = Carbon::now();
$start = $date->copy()->subWeeks(rand(1, 52));
$end = $date->copy()->addWeeks(rand(1, 52));
or
$date = CarbonImmutable::now();
$start = $date->subWeeks(rand(1, 52));
$end = $date->addWeeks(rand(1, 52));
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi there,
I've got a "simple" issue here. Im trying to have Carbon give me a range of dates based on now. For a start date I want to remove some weeks, and for an end date I want to add some weeks from now. However with what I wrote below, I get the same date for both start and end.
Any idea why?
Thanks
$date = Carbon::now();
$start = $date->subWeeks(rand(1, 52));
$end = $date->addWeeks(rand(1, 52));
logger($start . ' == ' . $end);
// Logs: local.DEBUG: 2021-07-08 07:57:23 == 2021-07-08 07:57:23
// not only that but I also get dates in the future even for start: 2022-07-14 07:57:23 == 2022-07-14 07:57:23
You are mutating the date.. Carbon overwrites the date on the object. You need to clone it
$date = Carbon::now();
$start = $date->clone()->subWeeks(rand(1, 52));
$end = $date->clone()->addWeeks(rand(1, 52));
//or create a new instance for each
$start = Carbon::now()->subWeeks(rand(1, 52));
$end = Carbon::now()->addWeeks(rand(1, 52));
// or cast to immutable
$date = Carbon::now()->toImmutable();
$start = $date->subWeeks(rand(1, 52));
$end = $date->addWeeks(rand(1, 52));
edit: ->clone() and ->copy() are just aliases of each other. They do the same thing
Please or to participate in this conversation.