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

Adding a time to randomly generated list of dates

在下面,我试图生成一个日期数组,这些日期满足自 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;
}

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