You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Carbon包为指定条件生成的日期统一添加晚7点时间?

Yes, Carbon is absolutely up for this task!

You’re already on the right track using Carbon—let’s tweak your code to reliably generate the dates you need (Sundays, Mondays, Thursdays starting from 1990) and set all events to 7 PM automatically.

First, let’s align with your core requirements:

  • Generate all dates falling on Sunday, Monday, or Thursday from January 1, 1990, up to one month from today
  • Set every event’s date field to 7 PM on those days
  • Clean up the date generation logic to avoid gaps or duplicates

Here’s a refined, reliable implementation:

public function run()
{
    $startDate = Carbon::parse('1990-01-01');
    $endDate = Carbon::now()->addMonth();
    $targetWeekdays = ['sunday', 'monday', 'thursday'];
    $eventTime = '19:00:00'; // Fixed 7 PM time

    // Collect all valid dates
    $validDates = collect();
    $currentDate = $startDate->copy();

    // Iterate day-by-day to ensure no dates are missed
    while ($currentDate->lte($endDate)) {
        // Check if the current day is one of our targets
        if (in_array(strtolower($currentDate->format('l')), $targetWeekdays)) {
            // Set the time to 7 PM and add to our collection
            $eventDate = $currentDate->copy()->setTimeFromTimeString($eventTime);
            $validDates->push($eventDate);
        }
        $currentDate->addDay();
    }

    // Create events and filter for those within the next 2 weeks
    $events = $validDates->sort()->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));
    });

    // Optional: Use $events for further processing
    // dd($events);
}

Why this works better:

  1. No missed dates: Starting from 1990-01-01 and iterating day-by-day ensures we don’t skip early valid Sundays/Thursdays in January 1990 (your original code started on the first Monday of 1990, which would miss these).
  2. Easy time setting: setTimeFromTimeString($eventTime) reliably sets every date to 7 PM without extra convoluted logic.
  3. Clearer logic: The day-by-day check is straightforward and easier to debug than modifying dates with relative strings like "last monday of next month".

For better performance (great for large time spans):

If you’re worried about iterating 30+ years of days, you can optimize by generating dates month-by-month instead:

public function run()
{
    $startDate = Carbon::parse('1990-01-01');
    $endDate = Carbon::now()->addMonth();
    $targetWeekdays = ['sunday', 'monday', 'thursday'];
    $eventTime = '19:00:00';

    $validDates = collect();
    $currentMonth = $startDate->copy()->startOfMonth();

    while ($currentMonth->lte($endDate)) {
        foreach ($targetWeekdays as $day) {
            // Get the first occurrence of the day in the month
            $currentDay = $currentMonth->copy()->firstOfMonth()->modify($day);
            // If the first occurrence is in the previous month, jump to the next week
            if ($currentDay->month !== $currentMonth->month) {
                $currentDay->addWeek();
            }
            // Add all occurrences of the day in the current month
            while ($currentDay->month === $currentMonth->month && $currentDay->lte($endDate)) {
                $eventDate = $currentDay->copy()->setTimeFromTimeString($eventTime);
                $validDates->push($eventDate);
                $currentDay->addWeek();
            }
        }
        $currentMonth->addMonth();
    }

    // Create events and filter (same as before)
    $events = $validDates->sort()->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));
    });
}

This version loops through each month instead of each day, which is much faster for long time ranges while still capturing all valid dates.

内容的提问来源于stack exchange,提问作者user3732216

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:43:47