In this post, I will show you a simple example of Laravel Carbon subtract days. You will learn how to subtract days using Carbon in Laravel. If you need to subtract one day or multiple days from the current date in Laravel, this post will guide you through it.
Laravel provides the Carbon library, which is a powerful tool for handling date and time. To subtract days from a date, you can use the subDay() or subDays() methods provided by Carbon. These methods allow you to easily manipulate dates within your Laravel tasks.
Laravel Carbon subtract days from a Date with examples
Carbon is included by default in Laravel, so you can begin using it immediately.
Example 1: Laravel carbon Subtract day from current date
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index()
{
$currentDate = Carbon::now();
$newDateTime = Carbon::now()->subDay();
print_r($currentDate); // Show current date
print_r($newDateTime); // 1 days will be substracted from the current date
}
}
Example 2: Laravel carbon subtract days example
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index()
{
$currentDate = Carbon::now();
$newDateTime = Carbon::now()->subDays(5);
print_r($currentDate); // Show current date
print_r($newDateTime); // 5 days will be substracted from the current date
}
}
Example 3: Subtract days from a specific date
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index()
{
$specificDate = Carbon::createFromFormat('Y-m-d', '2022-12-08');
$newDateTime = Carbon::now()->subDays(5);
print_r($newDateTime); // 5 days will be substracted from the specific date
}
}
I hope this tutorial help you.