How to Add Hours To Date using Carbon – Laravel

The Carbon PHP API enables us to perform multiple functions to manage dates and times and multiple time zones in a Laravel application. Most Importantly, its feature to add or subtract times and dates. Let’s go through the process how the API makes it easy to add hours to a time from the date object in a Laravel application.

Carbon provides us with functions like addHour() and addHours() that can add one or more hour to a given date time object in Laravel. These functions will allow us to change the hours from the date time object. Let’s demonstrate this in an example where we add hours to a date returned from the Carbon::now() helper function.

For example, the sample code below takes the current date and time and passes the addHour() function to it. This adds one hour to the date time object. Since it is the hour function, we don’t need to specify the number of hours here. This will always add up just a single hour.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addHour();
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

Hence, the output to the code above is as shown below.

Current Date and Time : 2023-01-31 10:30:34
Current Date with Add Hours : 2023-01-31 11:30:34

You can use the addHours() function by Carbon to add hours as per your requirements. So, here we will go through an example where we can add any specified number of hours to the date time object.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addHours(8);
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

As a result, the code above will add 8 hours to the date returned. The output is as shown below.

urrent Date and Time : 2023-01-31 10:30:34
Current Date with Add Hours : 2023-01-31 06:30:34