为随机生成的日期列表添加时间

时间:2018-05-28 13:49:50

标签: php laravel php-carbon

下面我试图生成一系列日期,这些日期符合自1990年以来的星期日,星期一和星期四的标准。有了这些日期,我想为每个创建的活动添加一个晚上7点的时间。这可能与Carbon包有关吗?

public function run()
{
    $start = Carbon::parse('First Monday of January 1990');
    $nextMonth = Carbon::now()->addMonth();

    collect([
        'monday' => false,
        'thursday' => false,
        'sunday' => true
    ])->flatMap(function ($bool, $day) use ($start, $nextMonth) {
        return $this->dates($start, $nextMonth, $day, $bool);
    })->sort(function ($a, $b) {
        return strtotime($a) - strtotime($b);
    })->values()->map(function ($date, $key) {
        return factory(Event::class)->create([
            'name' => 'Event '.($key + 1),
            'slug' => 'event'.($key + 1),
            'venue_id' => Venue::inRandomOrder()->first()->id,
            'date' => $date
        ]);
    })->filter(function ($event) {
        return $event->date->lte(Carbon::today()->addWeeks(2));
    });
}

protected function dates(Carbon $from, Carbon $to, $day, $last = false)
{
    $step = $from->copy()->startOfMonth();
    $modification = sprintf($last ? 'last %s of next month' : 'next %s', $day);

    $dates = [];
    while ($step->modify($modification)->lte($to)) {
        $dates[$step->timestamp] = $step->copy();
    }

    return $dates;
}

1 个答案:

答案 0 :(得分:1)

要添加晚上7点的时间,您可以使用Carbon setter方法$date->hour = 19。见http://carbon.nesbot.com/docs/#api-setters