Examine this self-explanatory code in PHP:
Reality:
$dateTime = Carbon::createFromDateTime(2017, 2, 23);
echo $dateTime; // 2017-02-23 00:00:00
echo $dateTime->startOfYear(); // 2017-12-31 23:59:59
echo $dateTime; // 2017-12-31 23:59:59
Notice that on the 4th line, the value of $dateTime
is 2017-12-31 23:59:59
. That is because on the 3rd line.
But why? I know that Carbon's startOfYear() is a modifier, but how can we therefore get a date's start of the year without modifying itself
Expected:
$dateTime = Carbon::createFromDateTime(2017, 2, 23);
echo $dateTime; // 2017-02-23 00:00:00
echo $dateTime->startOfYear(); // 2017-12-31 23:59:59
echo $dateTime; // 2017-02-23 00:00:00
Above, notice the 4th line. In reality, the 4th line outputs 2017-12-31 23:59:59
.
Just like @SteD mentioned, you could use copy function to get existing instance and not modifying it.
$date = Carbon::createFromDate(2017, 2, 23);
$startOfYear = $date->copy()->startOfYear();
$endOfYear = $date->copy()->endOfYear();
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