Mastering Date Manipulation in Laravel using Carbon

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

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

In this article we will learn how can you add or substract custom amount of days 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 day to day development . So lets see how to use Carbon in Laravel to add or substract days from any date and time .

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

UserController.php :

public function carbonDays()
    {
      $time = User::find('1')->created_at;   // 2020-12-27T07:54:06.000000Z

      // Adding Days to the DateTime
      
      $time->addDay();                    // 2020-12-28T07:54:06.000000Z 

      $time->addDays(5);                  // 2021-01-02T07:54:06.000000Z

      // Substracting Days from DateTime
      
      $time->subDay();                    // 2021-01-01T07:54:06.000000Z

      $time->subDay(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