How to Add Days To Date using Carbon -Laravel

The Carbon PHP API enables us to perform multiple functions to manage dates and times and multiple time zones in a Laravel application. Most Importantly, its feature to add or subtract times and dates. Let us go through the process how the API makes it easy to add days to date in a Laravel application.

Carbon provides us by default with addDay() and addDays() functions. We can use these methods to add days on a date object. Let’s look at some code samples which demonstrate this feature.

The controller below shows the index function, where current date is returned using the Carbon::now() helper function. This date can then be manipulated by adding any number of day or days to it using the addDay() and addDays() functions respectively.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addDay();
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

The example above uses the addDay() function. Therefore, there is no need to pass the day number here, as add Day means, only one day adds to the current date.

The code above displays the output as shown below.

Carbon\Carbon Object
(
    [date] => 2023-01-31 04:29:35.435461
    [timezone_type] => 3
    [timezone] => UTC
)

Carbon\Carbon Object
(
    [date] => 2023-02-01 04:29:35.435474
    [timezone_type] => 3
    [timezone] => UTC
)

The first date object returns the current date, listing all components of the date and time separately. The second one returns the date after adding a day to it. Notice, the next day date seen in the second object.

Similarly, we can also use the addDays() function to add any number of days to a given or current date. Consider the code sample below.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addDays(8);
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

Here the add Days function will take a parameter that specifies the number of days to add. As in the code sample above, it is addDays(8) adding 8 days to the original date returned using the Carbon::now() helper function.

The output for this code will be as shown below.

Carbon\Carbon Object
(
    [date] => 2023-01-31 04:29:35.435461
    [timezone_type] => 3
    [timezone] => UTC
)

Carbon\Carbon Object
(
    [date] => 2023-02-07 04:29:35.435474
    [timezone_type] => 3
    [timezone] => UTC
)