How to Add Years 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’s go through the process of how to add years to a given or current date in a Laravel application.

Carbon provides us by default with addYear() and addYears() functions. We can use these methods to add a year on a date object. The function will add the next year or multiple years to a given date. Usng these functions you can change the years from 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 year or years to it using the addYear() and addYears() 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()->addYear();
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

The example above uses the addYear() function. Therefore, there is no need to pass a number for how many years to add, as add Year means, only a single year adds to the current date.

The code above displays the output as shown below.

Current Date and Time : 2023-02-20 10:15:05
Current Date with Add Year : 2023-02-20 10:15:05

You can make us of the addYear() function by Carbon to add any number of years as per your requirements. So, lets consider an example to add 3 years to a given date.

<?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()->addYears(3);

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

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

The output for adding 3 years in the code above is as shown below.

Current Date and Time : 2023-02-20 10:15:05
Current Date and Time : 2026-02-20 10:15:05