Php 更新变量时更改LAVEL日期

Php 更新变量时更改LAVEL日期,php,laravel,laravel-5,php-carbon,Php,Laravel,Laravel 5,Php Carbon,我正在编写一个范围查询,并传入一个fetch\u date,以便根据在时间戳处创建的从DB表中提取内容 我试图查找一个月的所有记录,但每当我尝试以下操作时,变量$fetch\u date都会不断更改: //$fetch_date is a carbon instance and is equal to the month the user selected //ie: Carbon {#221 ▼ // +"date": "2016-07-01 00:00:00.

我正在编写一个范围查询,并传入一个
fetch\u date
,以便根据在
时间戳处创建的
从DB表中提取内容

我试图查找一个月的所有记录,但每当我尝试以下操作时,变量
$fetch\u date
都会不断更改:

    //$fetch_date is a carbon instance and is equal to the month the user selected 
    //ie: Carbon {#221 ▼
    //    +"date": "2016-07-01 00:00:00.000000"

    //Create the next_month
    $next_month = $fetch_date->addMonth();
    //Format next_month as a string
    $next_month = $next_month->format('Y-m-d');
    //Format fetch_date as a string
    $fetch_date = $fetch_date->format('Y-m-d');

    dd($fetch_date);
    //This now gives me 2016-08-01 - why?
为什么
fetch\u日期
会改变?基本上,我试图将
$fetch\u date
保持为当前月份,将
$next\u month
保持为下个月的开始


我想我忽略了一个非常简单的原因。

似乎您在fetch\u date变量中添加了一个月

试试这个:

$next_month = Carbon::createFromFormat('Y-m-d', $fetch_date->format('Y-m-d'));
$next_month->addMonth();

dd($next_month->format('Y-m-d'));
请看一下碳的文档:
可能会对您有所帮助,因为调用
addMonth
方法会产生副作用

如果你看Carbon's,你会发现
addMonth
所做的一切都是调用
addMonths
,值为1,这反过来就是调用。文档中没有明确说明,但从示例中可以很清楚地看出,调用该方法会修改存储的时间值:

示例#1 DateTime::modify()示例


我认为您在fetch_date变量中添加了一个月。试着复制它,然后加上月份。好吧,我试过了。出于某些疯狂的原因,即使将其更改为您在此处所做的操作,$fetch_date仍然会更改。我想知道我的浏览器是否缓存了一些奇怪的东西——因为我不知道怎么可能……尝试新的解决方案,创建一个名为next_mont的新碳对象——并准确地解释发生了什么。谢谢你的详细解释;现在我明白了,你的纠正工作解决了这个问题。嗯,为什么要添加month/clone对象,而你本可以简单地使用php的strotime来达到想要的效果。另一方面,它也可以在一行中使用碳拷贝的方法来完成。
<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>
$also_fetch_date = clone $fetch_date;
$next_month = $also_fetch_date->addMonth();
// ...