首页 > 解决方案 > 如何从日期范围内添加星期几名称

问题描述

我正在使用 Laravel 和 Carbon。

我创建了一个函数来添加“可用性”,例如:

public function createAvailability(Request $request) {
    $availability = new Availability($request->all());
    $availability->save();

    return Redirect::back();
}

我发送“开始”和“结束”数据来请求,所以示例数据是:$request->start = '01/07/2018'; $request->end= '22/07/2018';

现在我插入数据库数据,如:

在此处输入图像描述

我想要做的是在数据库中插入数据,例如:

在此处输入图像描述

所以在前 7 天,我想插入具有相同“开始”和“结束”数据的名称......或者如果开始日期是 01/07 并且结束日期是 03/07 我只想插入 3 天周名...

我怎么能这样做?

这也是我的可用性类与受保护的日期:

class Availability extends Model
{

    protected $dates = [ 'start','end' ];

    public function setStartAttribute($date) {
        $this->attributes['start']= Carbon::createFromFormat('d/m/Y', $date);
    }

    public function getStartAttribute($date){
        return (new Carbon($date))->format('d-m-Y');
    }

    public function setEndAttribute($date) {
        $this->attributes['end']= Carbon::createFromFormat('d/m/Y', $date);
    }

    public function getEndAttribute($date){
        return (new Carbon($date))->format('d-m-Y');
    }
}

标签: phplaraveldatedate-rangephp-carbon

解决方案


我想这可能是你想要的

function days($start, $end){
  $current = strtotime($start);
  $end = strtotime($end);
  while($current <= $end && $current <= ($current * 7))){ // go until the last day or seven days, whichever comes first
    $day = date("l", $current);
    $availability = new Availability();
    $availability->start_date = date('d/m/Y', $current);
    $availability->end_date = date('d/m/Y', $end);
    $availability->day_of_week = date("l", $current);
    $availability->save();
    $current = $current + 86400;
}
days($request->input('start'), $request->input('end'));   

推荐阅读