Laravel Carbon Add Hours Tutorial with Example

Laravel Carbon add hours example: In this tutorial you will learn how to add an hour, add hours, add sub hour, and add sub hours in Laravel 9 application with the help of the PHP Carbon package.

By default this Laravel add hour example is built with Laravel 9; but, you can use the similar approach in the older versions like Laravel 5 | 6 | 7 | 8.

Example 1: Add Hour Using Carbon

This example add one hour in your currunt time. If you want to add manual or dynamic hour then go to example 2.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class CalenderController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addHour();
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

Example 2: Add Manual Hours

Using this example you can add manual or dynamic hours to adding in currunt date using laravel carbon.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class CalenderController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addHours(5);
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

Example 3: Sub Hour unsing Carbon

Just like add hour your can subtract hour using carbon.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class CalenderController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->subHour();

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

Example 4: Subtract Manual Hour

You can sub the hour for your requirement hours.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class CalenderController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->subHours(2);
  
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

So, today you learned how to add hours and sub hours with the Carbon module in the Laravel application.

Leave a Comment