Laravel Carbon Add Years Example Tutorial


Share:
Published By: Admin, Published On: Aug 10, 2021, Category: PHP Laravel 8 Laravel


Hi Guys,

Today, In this Example, i will explain how to add years in laravel using carbon in laravel so it can easy to use in laravel app.

So,if you needed to add one year or more years you can use carbon in laravel. carbon provide inbuilt function addYear() and addYears() method to Sub months on carbon date object. so let's see some examples to Sub month and months.

Here, I will give you a full example of how to add years in laravel using carbon in laravel. so follow my example code and you can use your laravel application to copy that code.

Example : 1
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class HomeController extends Controller
{
    /**
     * laravel carbon add year..
     *
     * @return string
    */
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addYear();

        // echo "<pre />";
        print_r($currentDateTime);
        print_r($newDateTime);
    }

}
Output
Carbon\Carbon Object

(
    [date] => 2021-08-10 06:15:27.618571

    [timezone_type] => 3

    [timezone] => UTC
)

Carbon\Carbon Object

(
    [date] => 2022-08-10 06:15:27.618574

    [timezone_type] => 3

    [timezone] => UTC
)
Example : 2
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class HomeController extends Controller
{
    /**
     * laravel carbon add years..
     *
     * @return string
    */
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addYears(2);

        // echo "<pre />";
        print_r($currentDateTime);
        print_r($newDateTime);
    }

}
Output
Carbon\Carbon Object

(
    [date] => 2021-08-10 06:18:29.743060

    [timezone_type] => 3

    [timezone] => UTC
)

Carbon\Carbon Object

(
    [date] => 2023-08-10 06:18:29.743069

    [timezone_type] => 3

    [timezone] => UTC
)

I Hope It Will Help You..

Share: