Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

garrettmassey's avatar

Carbon method subDays returning incorrect values

I am using Carbon to query data from the past two weeks, so I have a variable $now for today's date, and I loop the query over a for-loop and use $now->subDays($i) to get today, yesterday, the day before, etc, up to 14 days ago. I knew something was wrong because the query was returning null results (i.e it was trying to query for a date that didn't exist in the set), so I dumped the actual dates that were being passed in and formatted them as $now->subDays($i)->format('Y-m-d') and this is what I got:

"2022-03-31"
"2022-03-30"
"2022-03-28"
"2022-03-25"
"2022-03-21"
"2022-03-16"
"2022-03-10"
"2022-03-03"
"2022-02-23"
"2022-02-14"
"2022-02-04"
"2022-01-24"
"2022-01-12"
"2021-12-30"

The dates are incorrect... Obviously 2021-12-30 is not 14 days before 2022-03-31, and I have no idea what is happening to cause this.

Here is the raw for-loop that dumps the dates and decreases the date by one day:

$date = Carbon::now();
for ($i = 0; $i < 14; $i++) {
    dump($date->subDays($i)->format('Y-m-d'));
}
0 likes
3 replies
MichalOravec's avatar
Level 75

You need to create a copy() of an existing Carbon instance ($now).

$now->copy()->subDays($i)->format('Y-m-d') 
1 like
garrettmassey's avatar

@MichalOravec Thank you! I didn't know that the copy() method existed, and I also didn't know that using subDays() changed the original carbon object.

MichalOravec's avatar

@garrettmassey Also you can use CarbonPeriod.

$period = CarbonPeriod::create(now()->subDays(13), '1 day', now())->map(function ($date) {
    return $date->toDateString();
});

$dates = array_reverse(iterator_to_array($period));

Please or to participate in this conversation.