How to subtract days from current date using PHP Carbon – Laravel

The Carbon PHP API has many function that help manage dates and times and multiple time zones in a Laravel application. Most Importantly, its feature to add or subtract times and dates. A complex function that cannot be possible with simple code logic, and often requires helper functions or a strong API like Carbon to do so. Let us go through the process how the API makes it easy to subtract days from current date in a Laravel application.

You can use the simple Carbon helper functions as shown below.

Carbon::now()->addDays(3);
Carbon::now()->subWeekDays(3);

In the first line, 3 days are added to the current date. The second one subtracts 3 working days.

The flexible API has support to manage working days and entire week differences also!

You can use many Carbon supported helper functions to add or subtract days accordingly. To subtract any number of days from the current date, we use the following.

$date = Carbon::now()->subDays(7);

This subtracts 7 days from the current date.

Another case: 30 days prior date from current date.

$date = Carbon::now()->subDays(30);

To perform the same using PHP you can do the following.

$date = date('Y-m-d', strtotime("-7days");
$date = date('Y-m-d', strtotime("-30 days");

Notice the difference and how simple is it to use the Carbon library as compared to PHP code shown above.

You can also parse results obtained from Carbon library after adding or subtracting days as shown below.the

$date_final=Carbon::parse($start)->subWeekdays(1)->toDateString();