Laravel 更新变量时日期发生变化
Laravel date changing when I update a variable
我正在编写一个范围查询,我正在传递一个 fetch_date
以根据 created_at
时间戳从数据库 table 中提取内容。
我正在尝试查找一个月的所有记录,但每当我尝试以下操作时,变量 $fetch_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_date
会改变?我实际上是在尝试将 $fetch_date
保持为当前月份,将 $next_month
保持为下个月的开始。
我猜我忽略了一个真正简单的原因。
您似乎要向 fetch_date 变量添加一个月。
试试这个:
$next_month = Carbon::createFromFormat('Y-m-d', $fetch_date->format('Y-m-d'));
$next_month->addMonth();
dd($next_month->format('Y-m-d'));
看看 Carbon 的文档:http://carbon.nesbot.com/docs/
也许会对你有所帮助
因为调用addMonth
方法有副作用。
如果你看看 Carbon 的 source, you'll see that all addMonth
is doing is calling addMonths
with a value of 1, which in turn is simply calling DateTime::modify
。它没有在文档中明确说明,但从示例中可以很明显地看出调用该方法会修改存储的时间值:
Example #1 DateTime::modify() example
<?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();
// ...
我正在编写一个范围查询,我正在传递一个 fetch_date
以根据 created_at
时间戳从数据库 table 中提取内容。
我正在尝试查找一个月的所有记录,但每当我尝试以下操作时,变量 $fetch_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_date
会改变?我实际上是在尝试将 $fetch_date
保持为当前月份,将 $next_month
保持为下个月的开始。
我猜我忽略了一个真正简单的原因。
您似乎要向 fetch_date 变量添加一个月。
试试这个:
$next_month = Carbon::createFromFormat('Y-m-d', $fetch_date->format('Y-m-d'));
$next_month->addMonth();
dd($next_month->format('Y-m-d'));
看看 Carbon 的文档:http://carbon.nesbot.com/docs/ 也许会对你有所帮助
因为调用addMonth
方法有副作用。
如果你看看 Carbon 的 source, you'll see that all addMonth
is doing is calling addMonths
with a value of 1, which in turn is simply calling DateTime::modify
。它没有在文档中明确说明,但从示例中可以很明显地看出调用该方法会修改存储的时间值:
Example #1 DateTime::modify() example
<?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();
// ...