Laravel Carbon Add Hours Example Tutorial


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


Hi All,

Today, In this tutorial I will share with you how to add hours laravel using carbon in laravel so it can easy to use in laravel app.

Whenever, if you needed to add hour or more hours then you can use carbon in laravel. carbon provide inbuilt function addHour() and addHours() method to add hours on carbon date object. so let's see some examples to adding hour and hours.

Here, I will give you a full example of how to add hour and hours in laravel using carbon. 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 an hour.
     *
     * @return string
    */
    public function index(Request $request)
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addHour();

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

}
Output
Carbon\Carbon Object

(
    [date] => 2021-08-12 04:28:39.692169

    [timezone_type] => 3

    [timezone] => UTC
)

Carbon\Carbon Object

(
    [date] => 2021-08-12 05:28:39.692172

    [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 two hours..
     *
     * @return string
    */
    public function index(Request $request)
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addHours(2);

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

}
Output
Carbon\Carbon Object

(
    [date] => 2021-08-12 04:30:10.216053

    [timezone_type] => 3

    [timezone] => UTC
)

Carbon\Carbon Object

(
    [date] => 2021-08-12 06:30:10.216057

    [timezone_type] => 3
    
    [timezone] => UTC
)

I Hope It Will Help You..

Share: