laravel 如何在不修改过程中获得 Carbon 实例的开始和/或结束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42406461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get start and or end of year of a Carbon instance without modifying it in the process?
提问by doncadavona
Examine this self-explanatory code in PHP:
在 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.
请注意,4号线,价值$dateTime
为2017-12-31 23:59:59
。那是因为在第三行。
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
但为什么?我知道 Carbon 的 startOfYear() 是一个修饰符,但是我们如何才能在不修改自身的情况下获得年份的开始日期
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
.
注意上面的第 4 行。实际上,第 4 行输出2017-12-31 23:59:59
.
回答by Saravanan Sampathkumar
Just like @SteD mentioned, you could use copy function to get existing instance and not modifying it.
就像@SteD 提到的那样,您可以使用复制功能来获取现有实例而不是修改它。
$date = Carbon::createFromDate(2017, 2, 23);
$startOfYear = $date->copy()->startOfYear();
$endOfYear = $date->copy()->endOfYear();
回答by SteD
use copy()
用 copy()
From the docs
从文档
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.
您还可以创建现有 Carbon 实例的 copy() 。正如预期的那样,日期、时间和时区值都被复制到新实例中。
$dt = Carbon::now();
echo $dt->diffInYears($dt->copy()->addYear()); // 1
// $dt was unchanged and still holds the value of Carbon:now()
回答by R. Smith
You're replacing the value of the $datetime variable in line 3. Effectively:
您正在替换第 3 行中 $datetime 变量的值。有效地:
$a = 1;
echo $a;
$a = 2;
echo $a;
To fix this, you would need to do something like this:
要解决此问题,您需要执行以下操作:
$dateTime = Carbon::createFromDateTime(2017, 2, 23);
$startTime = $dateTime;
echo $dateTime->startOfYear();
Now you would have both dates. There may be more ways to skin the cat, but without knowing more about carbon, this is the simplest way to keep both.
现在你会有两个日期。可能有更多的方法来给猫剥皮,但在不了解更多碳的情况下,这是同时保留两者的最简单方法。