Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get start and or end of year of a Carbon instance without modifying it in the process?

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.

like image 791
doncadavona Avatar asked Feb 23 '17 03:02

doncadavona


1 Answers

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();
like image 128
Saravanan Sampathkumar Avatar answered Nov 15 '22 05:11

Saravanan Sampathkumar