To add days to a date using Carbon in PHP, follow these steps:
Install Carbon if you haven't already. You can do this using Composer by running the following command in your terminal:
composer require nesbot/carbon
Import the Carbon class at the beginning of your PHP file:
use Carbon\Carbon;
Create an instance of the Carbon class and parse the initial date. You can pass the initial date as a string or use a predefined format:
$date = Carbon::parse('2022-10-15');
// or
$date = Carbon::createFromFormat('Y-m-d', '2022-10-15');
Use the addDays()
method to add the desired number of days to the date. This method modifies the instance itself and returns a new instance of Carbon:
$newDate = $date->addDays(7);
// adds 7 days to the date and returns a new Carbon instance
Format and display the new date using the format()
method, if needed:
echo $newDate->format('Y-m-d');
// prints the new date in the specified format
That's it! You have successfully added days to a date using Carbon in PHP.