Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uniqueginun's avatar

Carbon generate period and give only days in the past.

If I have a given year and month and I want to generate the period from start to end of this month and exclude days which are yet to come? is there a simple way to do that?

        $month = $request->month ?? date('m');
        $year = $request->year ?? date('Y');

        $start = Carbon::create($year, $month)->startOfMonth();
        $end = Carbon::create($year, $month)->endOfMonth();

        $period = CarbonPeriod::create($start, $end); 

        foreach($period as $day)
        {
            if($day->isPast())
            {
                //do something
            }
        }
0 likes
1 reply
automica's avatar

You should check your created date against todays date and then you can limit it to your last day being yesterday by using ->subDay()

$day = Carbon::now()->format('d');

$end = Carbon::create($year, $month, $day)->isFuture() ? Carbon::now()->subDay() : Carbon::create($year, $month)->endOfMonth();

You'll also want to so a similar check for start to prevent dates in the future.

Please or to participate in this conversation.