How to Add and Subtract Years in Laravel with Carbon

The Carbon library is an excellent tool for working with dates and times in Laravel. It makes it easy to add and subtract years, months, days, and hours from dates, and to format dates in a variety of ways. In addition, it includes a number of helpful methods for comparing dates and calculating dates and time.

In this snippet, we’ll use Carbon to add and subtract years from a given date.

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{

    public function index()
    {
        
        //add years
        $now = Carbon::now();
        $oneYearLater = $now->addYear(1); 
        $fiveYearsLater = $now->addYear(5); 
        $tenYearsLater = $now->addYear(10); 

        //subtract years
        $twoYearsBefore = $now->subYear(1); 
        $fiveYearsBefore = $now->subYear(5); 
        $oneHundredYearsBefore = $now->subYear(100); 

    }
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close