如何从日期范围内添加星期几名称

时间:2018-06-29 16:54:12

标签: php laravel date date-range php-carbon

我正在使用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';

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

enter image description here

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

enter image description here

因此,对于前7天,我想插入具有相同“开始”和“结束”数据的名称...或者如果开始日期为01/07且结束日期为03/07,我只想插入3天与星期几的名称...

我该怎么做?

这也是我的Availablity类,具有受保护的日期:

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');
    }
}

1 个答案:

答案 0 :(得分:2)

我认为这可能是您想要的

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'));