php 使用 Carbon 递增日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35048657/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:20:11  来源:igfitidea点击:

Incrementing dates with Carbon

phplaravel-4php-carbon

提问by Kevin Daniel

I'm trying to create an array of blackout dates for a reservation system in Laravel 4. There is one test row in my db with a start_date of 2016-01-24 and end_date of 2016-01-29.

我正在尝试为 Laravel 4 中的预订系统创建一系列停电日期。我的数据库中有一个测试行,start_date 为 2016-01-24,end_date 为 2016-01-29。

This is the code that pulls the row and loops through the dates using Carbon to increment by one day & add it to an array:

这是使用 Carbon 拉出行并循环遍历日期以增加一天并将其添加到数组的代码:

$reserved = Reservation::where('property_id', $property->id)->get();

$blackoutDays = [];

foreach($reserved as $r)
{
    $start = new \Carbon\Carbon($r->start_date);
    $end = new \Carbon\Carbon($r->end_date);
    $days = $start->diff($end)->days;

    for($i = 0; $i <= $days; $i++)
    {
        $date = '';
        $date = $start->addDays($i);

        $blackoutDays[] = $date->format('Y-m-j');
    }
}

What I'm trying to get in $blackoutDays is:

我想在 $blackoutDays 中得到的是:

["2016-01-24", "2016-01-25", "2016-01-26", "2016-01-27", "2016-01-28", "2016-01-29"]

[“2016-01-24”、“2016-01-25”、“2016-01-26”、“2016-01-27”、“2016-01-28”、“2016-01-29”]

But what I'm actually getting is this:

但我实际得到的是:

["2016-01-24", "2016-01-25", "2016-01-27", "2016-01-30", "2016-02-3", "2016-02-8"]

[“2016-01-24”、“2016-01-25”、“2016-01-27”、“2016-01-30”、“2016-02-3”、“2016-02-8”]

Does anyone know why this is happening / how to fix it? Is there a better way of doing this?

有谁知道为什么会这样/如何解决?有没有更好的方法来做到这一点?

回答by ArSeN

You do increment $ievery run of your for loop. So it adds 1 in the first run, 2 days in the second, 3 days in the third and so on.

您确实会增加$ifor 循环的每次运行。所以它在第一次运行时加 1,第二次加 2 天,第三次加 3 天,依此类推。

Therefore, you want to replace

因此,您要更换

$date = $start->addDays($i);

with

$date = $start->addDays(1);

Where you probably fell into the pit is the idea that the days are added from the $startdate object on every call, but this is not the case, as this object is not "Immutable".

您可能陷入困境的想法是$start每次调用时都从日期对象添加日期,但事实并非如此,因为该对象不是“不可变的”。

回答by Odin Thunder

For more cleaner result, you can use addDay() method:

为了获得更清晰的结果,您可以使用 addDay() 方法:

$date = $start->addDay();

But in fact this is exactly the same. Source code for addDay() method:

但实际上这是完全一样的。addDay() 方法的源代码:

/**
 * Add a day to the instance
 *
 * @param int $value
 *
 * @return static
 */
public function addDay($value = 1)
{
    return $this->addDays($value);
}