Carbon Add Days To Date In Laravel

In this tutorial, we will explore how to use Carbon to add days to a date in Laravel, whether you are working with Laravel 8, 9, or 10. Carbon provides the addDay() and addDays() methods, allowing you to effortlessly increase the number of days in a Carbon date object.

This tutorial covers the essential steps for adding days to a date in Laravel, using the add() and sub() functions provided by Carbon for manipulating date and time.

Let's dive into an example of adding days to a date in Laravel, whether you are using Laravel 8, 9, or 10, using the powerful features of Carbon.

Example: addDay()

Laravel's ability to add days to a date allows you to extend dates using Carbon.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addDay();
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

Output:

Carbon\Carbon Object
(
    [date] => 2022-01-16 06:36:25

    [timezone_type] => 2

    [timezone] => GMT
)

Carbon\Carbon Object
(
    [date] => 2020-01-17 06:36:25

    [timezone_type] => 2

    [timezone] => GMT
)

 

 

Example: addDays()

You can add days according to your specific needs using addDays(), as shown in the example below.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{
    public function index()
    {
        $currentDateTime = Carbon::now();
        $newDateTime = Carbon::now()->addDays(5);
             
        print_r($currentDateTime);
        print_r($newDateTime);
    }
}

Output:

Carbon\Carbon Object
(
    [date] => 2020-01-16 06:38:41

    [timezone_type] => 2

    [timezone] => GMT
)

Carbon\Carbon Object
(
    [date] => 2020-01-21 06:38:41

    [timezone_type] => 2

    [timezone] => GMT

 

Conclusion:

In conclusion, we've learned how to use Carbon, a powerful date and time manipulation tool in Laravel, to add days to a date. This skill is invaluable for various scenarios where date calculations are required.

Whether you're working with Laravel 8, 9, or 10, the addDay() and addDays() methods make it simple to extend date values, providing flexibility and precision.

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS