Carbon日期处理之复制日期

以下是官方文档摘抄

官方文档地址:
Carbon - A simple PHP API extension for DateTime.

You can also create a copy() of an existing Carbon instance. As expected the date, time and timezone values are all copied to the new instance.

$dt = Carbon::now();
echo $dt->diffInYears($dt->copy()->addYear());  // 1
// $dt was unchanged and still holds the value of Carbon:now()

You can use nowWithSameTz() on an existing Carbon instance to get a new instance at now in the same timezone.

$meeting = Carbon::createFromTime(19, 15, 00, 'Africa/Johannesburg');
// 19:15 in Johannesburg
echo 'Meeting starts at '.$meeting->format('H:i').' in Johannesburg.';                  // Meeting starts at 19:15 in Johannesburg.
// now in Johannesburg
echo "It's ".$meeting->nowWithSameTz()->format('H:i').' right now in Johannesburg.';    // It's 16:49 right now in Johannesburg.

如果直接对一个日期实例进行两次修改操作,比如,加减日期。则原本的对象也会被修改。则你的第二次修改,会受到第一次修改的影响

如果你想避免这种冲突,可以使用"->copy()",对原有日期进行一次完整的复制后,再操作。

或者使用"->nowWithSameTz()"得到一个新的实例,来使用、

发布了155 篇原创文章 · 获赞 0 · 访问量 860

猜你喜欢

转载自blog.csdn.net/u013866352/article/details/105402732