Carbon add days to next monday
Asked Answered
T

2

18

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

Tontine answered 30/8, 2017 at 9:30 Comment(0)
I
16

What you can do is determine the current date, get the start of the week (Monday) and add a week to get the next week.

$date = Carbon::create(2017, 8, 30);
$monday = $date->startOfWeek();
$mondayOneWeekLater = $date->addWeeks(1); // $date->addWeek();

Rinse and repeat for months and years but as Maritim suggests it's in the docs. ;-)
Source: http://carbon.nesbot.com/docs/

Islam answered 30/8, 2017 at 9:43 Comment(0)
A
45

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);
Andreaandreana answered 27/2, 2020 at 21:21 Comment(3)
thanx for sharing because it's not easy to find this in Carbon documentation. I found out you can use const instead of strings as parameter: Carbon::now()->next(Carbon::MONDAY);Arbitrament
Is also possible to write using ->isMonday(): $date = $date->isMonday() ? $date : $date->next(Carbon::MONDAY);Calabash
is() function compares integers with year, so $date->is(Carbon::MONDAY) won't work because Carbon::MONDAY is integer 1; It will only work if we do $date->is('monday'); we can check weekday by $date->weekday() === Carbon::MONDAY.Coriolanus
I
16

What you can do is determine the current date, get the start of the week (Monday) and add a week to get the next week.

$date = Carbon::create(2017, 8, 30);
$monday = $date->startOfWeek();
$mondayOneWeekLater = $date->addWeeks(1); // $date->addWeek();

Rinse and repeat for months and years but as Maritim suggests it's in the docs. ;-)
Source: http://carbon.nesbot.com/docs/

Islam answered 30/8, 2017 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.