Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carbon add days to next monday

Tags:

php

php-carbon

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

like image 380
Demaunt Avatar asked Aug 30 '17 09:08

Demaunt


People also ask

What does carbon :: now return?

Carbon::now returns the current date and time and Carbon:today returns the current date. This is a sample output.

What is Nesbot carbon?

An API extension for DateTime that supports 281 different languages.

How do we add days to carbon?

Carbon provides addDay() and addDays() method to add days on carbon date object. So, we will see laravel carbon add days or how to add days in date in laravel 8. Using the carbon add() and sub() function you can change on date and time.


2 Answers

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);
like image 177
IGP Avatar answered Oct 09 '22 18:10

IGP


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/

like image 16
Edwin Avatar answered Oct 09 '22 20:10

Edwin