【问题标题】:Laravel4 Carbon loop through weekLaravel4 碳循环一周
【发布时间】:2017-06-27 20:31:17
【问题描述】:

我正在尝试用碳循环遍历当前一周并在视图中显示每一天。

$current_mon 和 $current_sun 是从周一到周日选择当前周的下拉菜单。 我不知道如何度过这周剩下的时间(周二到周六)

    $tues = Carbon::now()->startOfWeek()->addDay(); 

是个坏主意!

我的控制器是:

$now = Carbon::now();
    $current_mon = Carbon::now()->startOfWeek();        
    $current_sun = Carbon::now()->endOfWeek()->format('d-M');
    $tues = Carbon::now()->startOfWeek()->addDay(); 
    return View::make('backend/menubuilder/edit')->with('id',$id)->withCurrent_mon($current_mon)->withCurrent_sun($current_sun)->withTues($tues);

请指教

【问题讨论】:

    标签: php laravel php-carbon


    【解决方案1】:

    使用DateIntervalDatePeriod

    控制器:

    $startDate = \Carbon::now()->startOfWeek();        
    $endDate = \Carbon::now()->endOfWeek();
    //Init interval
    $dateInterval = \DateInterval::createFromDateString('1 day');
    //Init Date Period from start date to end date
    //1 day is added to end date since date period ends before end date. See first comment: http://php.net/manual/en/class.dateperiod.php
    $datePeriod = new \DatePeriod($startDate, $interval, $endDate->modify('+1 day'));
    
    return View::make('backend/menubuilder/edit',[$datePeriod]);
    

    查看:

    @foreach($datePeriod as $datePeriodRow)
        {!! DateTime Object: See: http://php.net/manual/en/class.datetime.php !!}
        {{$datePeriodRow->format('d-M')}}
    @endforeach
    

    【讨论】:

    • 感谢您的代码。现在我认为是 8 天,因为 $endDate 也增加了 1 天。知道如何解决这个问题吗?
    • 在线$datePeriod...从$endDate->modify('+1 day') to $endDate`切换。
    【解决方案2】:

    好的,感谢神秘的回答,我明白了:

    控制器

    $startDate = Carbon::now()->startOfWeek();
        $endDate = Carbon::now()->endOfWeek();
        //Init interval
        $dateInterval = \DateInterval::createFromDateString('1 day');
        //Init Date Period from start date to end date
        //1 day is added to end date since date period ends before end date. See first comment: http://php.net/manual/en/class.dateperiod.php
        $dateperiod = new \DatePeriod($startDate, $dateInterval, $endDate);
    
        return View::make('backend/menubuilder/edit')->with('id',$id)->withDateperiod($dateperiod);
    

    这会显示从星期一到星期日的整个当前周 再次感谢

    【讨论】:

    • 提示:直接在View::make()函数中传递你的数据。如果要传递的变量超过 10 个,使用 ->with() 会很麻烦。
    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多