Laravel Pro Tip: Easily Add or Subtract Seconds with Carbon

 How to add or substract seconds 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 seconds 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 seconds from any date and time .

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

UserController.php :

public function carbonSeconds()
    {
      $time = User::find('1')->created_at;   // 2020-12-27T07:54:06.000000Z
    
      // Adding Seconds to the DateTime
      
      $time->addSecond();                    // 2020-12-27T07:54:07.000000Z   
      $time->addSeconds(50);                 // 2020-12-27T07:54:57.000000Z

      // Substracting seconds from DateTime
      
      $time->subSecond();                   // 2020-12-27T07:54:56.000000Z
      $time->subSecond(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