Carbon 2 Date 解析 returns 不同的结果

Carbon 2 Date parsing returns different results

所以我从 url 中得到一个日期,就像这样 2020-05-23 我试图将它解析成一个碳对象,所以下面的代码和平工作正常

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

那个returns这个:

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

什么是正确的,但是当我尝试获取本月的第一天和最后一天时它会更改变量?

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

它returns然后这个

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)
}

所以它将日期更改为 20202-05-31->firstOfMonth() returns 与 ->endOfMonth 相同 我没有正确解析日期?

同样,当我将 Carbon::parse('2020-05-23') 更改为 Carbon::now() 时,它工作正常,但日期当然不同

所以我发现了问题,但我不明白为什么会这样?

但是当只做 dd($newDate->firstOfMonth()) 它工作正常并且 return 是第一次约会但是当添加 $newDate->endOfMonth() 使其 dd($newDate->firstOfMonth(), $newDate->endOfMonth()) 它 return 两次$newDate->endOfMonth()的值有什么奇怪的?我不知道这是 laravel carbon 中的错误还是只是 php

var_dump

相同

日期实例是 mutable 这意味着当你做类似 $newDate->firstOfMonth() 的事情时它会改变 $newDate

你可以在文档的介绍中看到这个https://carbon.nesbot.com/docs/#api-introduction

所以当你

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

它会先执行firstMonth(),然后再执行endOfMonth(),然后再将参数传递给dd(),由于$newDate是可变的,参数内容将是参数内容的三倍月.

你可以做的是

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

Carbon::Parse returns 可变对象。这意味着这些方法将更改您正在使用的对象,而不是返回一个新对象并保持原始对象不变。

当您调用 dd 时,PHP 必须首先准备 3 个参数,以便它调用对象的两个方法,最后一个方法将日期更改为该月的最后一天。

如果你想让对象不可变,你必须使用CarbonImmutable

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

查看此处了解更多信息:https://carbon.nesbot.com/docs/