Save Time with Laravel: Adjust Date and Time Effortlessly

How to add or substract hours on a DateTime in Laravel using Carbon

Carbon - add or substract seconds from DateTime - Laravel

In this article we will learn how can you add or substract custom amount of hours to a perticular DateTime in Laravel .Carbon package provides us lots of flexibility with with it function to work with date and time in our development . So lets see how to use Carbon in Laravel to add or substract hours from any date and time .

We will take an example , we will retrieve a DateTime from  DB and then we will add and substract hours from it and convert it to human readable form .

UserController.php :

public function carbonHours()
    {
      $time = User::find('1')->created_at;   // 2020-12-27T07:54:06.000000Z
    
      // Adding hours to the DateTime
      
      $time->addHour();                    // 2020-12-27T08:54:06.000000Z  
      $time->addHours(5);                  // 2020-12-27T13:54:06.000000Z

      // Substracting hours from DateTime
      
      $time->subHour();                    // 2020-12-27T12:54:06.000000Z
      $time->subHours(5);                  // 2020-12-27T07:54:06.000000Z

      // Converting to Human readable form
      
      $time = $time->toDateTimeString();    // 2020-12-27 07:54:06
      return $time;
    }




Previous Post Next Post

Contact Form