用Carbon增加日期 [英] Incrementing dates with Carbon

查看:376
本文介绍了用Carbon增加日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Laravel 4中的预订系统创建一个停电日期数组.我的数据库中有一个测试行,其开始日期为2016-01-24,结束日期为2016-01-29.

这是使用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');
    }
}

我想要在$ 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-27","2016-01-30","2016-02-3","2016-02-8 ]

有人知道为什么会这样/如何解决吗?有更好的方法吗?

解决方案

在for循环的每次运行中,您都会递增$i.因此,它在第一次运行中添加了1,在第二次运行中添加了2天,在第三次运行中添加了3天,依此类推.

因此,您要替换

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

使用

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

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

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?

解决方案

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".

这篇关于用Carbon增加日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆