Incrementing dates with Carbon

2020-08-09 07:08发布

问题:

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.

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:

$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:

["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"]

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

回答1:

You do increment $i every 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.

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 $start date object on every call, but this is not the case, as this object is not "Immutable".



回答2:

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

$date = $start->addDay();

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

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