Time Control in Laravel: Add or Subtract Minutes from DateTime

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

Carbon - add or substract minutes from DateTime - Laravel

In this article we will learn how can you add or substract custom amount of minutes 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 minutes from any date and time .

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

UserController.php :

public function carbonMinutes()
    {
      $time = User::find('1')->created_at;   // 2020-12-27T07:54:06.000000Z
    
      // Adding minutes to the DateTime
      
      $time->addMinute();                    // 2020-12-27T07:55:06.000000Z  
      $time->addMinutes(50);                 // 2020-12-27T08:45:06.000000Z

      // Substracting minutes from DateTime
      
      $time->subMinute();                    // 2020-12-27T08:44:06.000000Z
      $time->subMinutes(50);                 // 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