Laravel Carbon Subtract Hours Example Tutorial


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


Hi Dev,

Today, In this example tutorial I will explain you how to subtract hours laravel using carbon in laravel so it can easy to use in laravel app.

Whenever, if you require to subtract one hour or more hours then you can use carbon in laravel. carbon provide inbuilt function subHour() and subHours() method to subtract hours. so let's see some examples to adding hour and hours.

I will give you a full example of how to subtract one 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 sub hour.
     *
     * @return string
    */
    public function index(Request $request)
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->subHour();

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

}
Output
Carbon\Carbon Object

(
    [date] => 2021-08-13 04:24:51.941708

    [timezone_type] => 3

    [timezone] => UTC
)

Carbon\Carbon Object

(
    [date] => 2021-08-13 03:24:51.941710

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

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

}
Output
Carbon\Carbon Object

(
    [date] => 2021-08-13 04:26:50.406806

    [timezone_type] => 3

    [timezone] => UTC
)

Carbon\Carbon Object

(
    [date] => 2021-08-13 02:26:50.406810

    [timezone_type] => 3

    [timezone] => UTC
)

I Hope It Will Help You..

Share: