Carbon add days to next monday

Demaunt picture Demaunt · Aug 30, 2017 · Viewed 9.3k times · Source

I have Carbon date variable.

Carbon::parse("2018-08-01") //tuesday

I want to add days until next monday ("2018-08-07").

Is there command like

 Carbon->addDaysUntil("monday"); ->addMonthUntil("september")

and so on.

So i want to change current date to begining of next week, month, year

Answer

IGP picture IGP · Feb 27, 2020

Old question but there's a nice way of doing this at the moment.

$date = Carbon::parse('2018-08-01')->next('Monday');

Additionally, if you want to check if your date is monday first, you could do something like this:

$date = Carbon::parse(...);
// If $date is Monday, return $date. Otherwise, add days until next Monday.
$date = $date->is('Monday') ? $date : $date->next('Monday');

Or using the Carbon constants as suggested by @smknstd in the comment below:

$date = Carbon::parse(...);
// If $date is Monday, return $date. Otherwise, add days until next Monday.
$date = $date->is(Carbon::MONDAY) ? $date : $date->next(Carbon::MONDAY);