php

Use of Laravel Carbon

Most web applications require to work with date and time. The web application developed by the Laravel framework uses a simple API extension to work with the date and time called Carbon. This PHP package can handle the time and timezone more easily in the Laravel project. The Carbon package can be used for many purposes, such as reading the current date and time, changing the default date and time format, finding the difference between two dates, converting the date and time from one timezone to another timezone, etc. Different uses of Carbon in the Laravel project have been shown in this tutorial.

Pre-requisites:

You have to complete the following tasks before practicing the examples of this tutorial.

Create a new Laravel project named timeProject. Here, the composer has been used to create the Laravel project. If the composer is not installed before then, you must install it before executing the following command.

$ composer create-project laravel/laravel timeProject

Go to the project folder.

$ cd timeProject

All examples of this tutorial have been tested in Laravel version 9+. Check the installed version of Laravel.

$ php artisan --version

Create a controller:

Run the following command to create a controller to check the uses of the Carbon package. After executing the command, the datetimeController.php file will be created inside the app/Http/Controllers folder.

$ php artisan make:controller datetimeController

Different uses of Carbon:

The uses of Carbon for different purposes have been shown in this part of the tutorial by modifying the datetimeController.php file.

Example-1: Read the current date and time

The simplest use of the Carbon class is to read the current date and time. Open the datetimeController.php file and replace the content with the following script. The now() function of the Carbon class has been used in the script to read the current date and time.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;

class datetimeController extends Controller
{
    public function index()
    {
        //Read the current date and time
    $current_datetime = Carbon::now();
    //Print the current date and time
    echo "The current date and time is $current_datetime";

    }
}

Open the web.php file from the routes folder, add the following lines to add the controller information, and run the index() function of the controller for the root URL.

use App\Http\Controllers\datetimeController;
Route::get('/',[datetimeController::class, 'index']);

Run the following command to start the Laravel development server if it is not started before.

$ php artisan serve

Run the following URL from the browser check the output of this example.

http://127.0.0.1:8000/

The following similar output will appear based on the date and time of the system.

Example-2: Format the current date and time

Replace the index() function of the datetimeController with the following script to know how to format the current date and time. Three different types of formatting have been shown in the following script. The date value will be printed with the dd-mm-yy format in the first output. The date value will be printed with the full month name and year value in the second output. The time value will be printed with the hh:mm:ss format in the third output.

public function index()
{
    //Read the current date and time
    $datetime = Carbon::now()->toDateTimeString();

    //Format the date to get the date only
    $cur_date = Carbon::createFromFormat('Y-m-d H:i:s', $datetime)->format('d-m-y');
    //Print the current date
    echo "The current date is $cur_date<br />";

    //Format the date to get the date in another way
    $cur_date2 = Carbon::createFromFormat('Y-m-d H:i:s', $datetime)->format('d F Y');
    //Print the current date
    echo "The current date in another format is $cur_date2<br />";

    //Format the date to get the time only
    $cur_time = Carbon::createFromFormat('Y-m-d H:i:s', $datetime)->format('h:i:s');
    //Print the current time
    echo "The current time is $cur_time";

}

The following similar output will appear based on the current date and time after executing the above script.

Example-3: Print the current, previous, and next date

Replace the index() function of the datetimeController with the following script to know how to print the current date, coming date, previous date.

public function index()
{
       $now = Carbon::now()->toDateString();
       $formmatted =  Carbon::createFromFormat('Y-m-d', $now)->format('F j, Y');
    echo "<b>Today:</b> $formmatted<br />";                            
   
    $nextDay = Carbon::tomorrow()->toDateString();
    $formmatted =  Carbon::createFromFormat('Y-m-d', $nextDay)->format('F j, Y');
    echo "<b>Tomorrow:</b> $formmatted<br />";                          
   
    $prevDay = Carbon::yesterday()->toDateString();
    $formmatted =  Carbon::createFromFormat('Y-m-d', $prevDay)->format('F j, Y');
    echo "<b>Yesterday:</b> $formmatted<br />";  

}

The following similar output will appear based on the current date and time after executing the above script.

Example-4: Find the difference between dates in days, months, and years

Replace the index() function of the datetimeController with the following script to know the way of calculating the difference between two dates in days, months, and years.

public function index()
{
       //Set the start date
       $start_date = Carbon::createFromFormat('Y-m-d', '2022-03-15');
       //Set the end date
    $end_date = Carbon::createFromFormat('Y-m-d', '2024-03-15');
   
    //Count the difference in days
    $count_days = $start_date->diffInDays($end_date);
    //Print the count value
    echo "The difference between two dates is $count_days days<br />";
   
    //Count the difference in months
    $count_months = $start_date->diffInMonths($end_date);
    //Print the count value
    echo "The difference between two dates is $count_months months<br />";
   
    //Count the difference in years
    $count_years = $start_date->diffInYears($end_date);
    //Print the count value
    echo "The difference between two dates is $count_years years";
}

The following output will appear after executing the above script.

Example-5: Set the default timezone

Another important use of the Carbon class is to set the timezone. Replace the index() function of the datetimeController with the following script to set two different timezones and check the time differences between the timezones.

public function index()
{
    //Set the default timezone
        date_default_timezone_set('America/Los_Angeles');
        $datetime = Carbon::now()->toDateTimeString();
        $date = Carbon::createFromFormat('Y-m-d H:i:s',$datetime)->format('d/m/Y h:i:s');
        echo $date,"<br />";
       
        //Change the default timezone
        date_default_timezone_set('Asia/Dhaka');
        $datetime = Carbon::now()->toDateTimeString();
    $date = Carbon::createFromFormat('Y-m-d H:i:s',$datetime)->format('d/m/Y h:i:s');
        echo $date;
}

The following similar output will appear based on the current date and time after executing the above script.

Conclusion:

The Carbon class is a very useful class of the Laravel to work with the date and time. Different methods of this class have been used in the examples of this tutorial to print date and time in different ways and perform date and time-related tasks.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.