Carbon 2 Date parsing returns different results

HashtagForgotName :

So Im getting a date from a url like this 2020-05-23 And Im trying to parse it into a carbon object so this following peace of code works fine

 $newDate = Carbon::parse('2020-05-23');
 dd($newDate);

that returns this:

Carbon\Carbon @1590192000 {#279 ▼
   date: 2020-05-23 00:00:00.0 UTC (+00:00)
}

what is correct but when I am trying to get the first and last day of this month it changes the variable?

$newDate = Carbon::parse($date);
//dd($newDate);
dd($newDate, $newDate->firstOfMonth(), $newDate->endOfMonth());

it returns then this

Carbon\Carbon @1590969599 {#279 ▼
   date: 2020-05-31 23:59:59.999999 UTC (+00:00)
}
Carbon\Carbon @1590969599 {#279 ▼
   date: 2020-05-31 23:59:59.999999 UTC (+00:00)
}
Carbon\Carbon @1590969599 {#279 ▼
   date: 2020-05-31 23:59:59.999999 UTC (+00:00)
}

so it changes the date towards 20202-05-31 ? and the ->firstOfMonth() returns the same as ->endOfMonth Im not parsing the the date correctly?

also when I change the Carbon::parse('2020-05-23') toward Carbon::now() it works fine but with different date of course

Clément Baconnier :

The date instance is mutable it means when you do something like $newDate->firstOfMonth() it will change $newDate

You can read this in the introduction of the documentation https://carbon.nesbot.com/docs/#api-introduction

So when you do

dd($newDate, $newDate->firstOfMonth(), $newDate->endOfMonth());

It will execute firstMonth() and then endOfMonth() before passing the parameters to dd() and since $newDate is mutable, the parameter content will be three time the end of month.

What you can do instead is

dd($newDate, $newDate->copy()->firstOfMonth(), $newDate->copy()->endOfMonth());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=15496&siteId=1