How to Add Months 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 months to a given or current date in a Laravel application.

Carbon provides us by default with addMonth() and addMonths() functions. We can use these methods to add a month on a date object. The function will add the next month or multiple months to a given date. 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 month or months to it using the addMonth() and addMonths() 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()->addMonth();
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

The example above uses the addMonth() function. Therefore, there is no need to pass a number for how many months to add, as add Month means, only a single month adds to the current date.

The code above displays the output as shown below.

Current Date and Time : 2023-01-20 07:03:05
Current Date with Add Month : 2023-02-20 07:03:05

Similarly, we can also use the addMonths() function to add any number of months 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()->addMonths(5);

        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

Here the add Months function will take a parameter to specify the number of months. As in the code sample above, it is addMonths(5) adding 5 months to the original date returned using the Carbon::now() helper function.

The output for adding 5 months in the code above is as shown below.

Current Date and Time : 2023-01-16 08:05:55
Current Date with Add Months : 2023-06-16 08:05:55