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
}
}
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 sign in or create an account to participate in this conversation.