How to Change Date Format in Laravel App with Carbon

Last updated on by Digamber

This is a quick tutorial about changing the date format in Laravel with Carbon, throughout this tutorial, you will learn how to change the date format in the Laravel 8 application using Carbon.

Carbon is a simple yet exorbitantly, powerful PHP based extension that offers intuitive methods to handle date-time.

When you get a task to change the date format in the laravel application, fret not; in that case, you can take Carbon class’s help to change the date format in laravel. With Carbon’s help, this task becomes you can invoke many methods that can make your date-time tasks facile.

Setting Up Laravel App

Run command to install a new laravel application:

composer create-project laravel/laravel --prefer-dist laravel-carbon-example

Run the application:

php artisan serve

Open below URL in browser:

http://127.0.0.1:8000

Thereafter, you require to generate a new controller, there you will create the logic to change the date format:

php artisan make:controller DateTimeController

Change Laravel Date Format Example

As we have created the DateTimeController now within the intuitive controller import the Carbon class. Next, we created a newDateFormat() function within this method you will have to write the logic to change the date format using Carbon.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;

class DateTimeController extends Controller
{

    public function newDateFormat()
    {
        $dateTime = date('Y-m-d H:i:s');
        $updatedDateFormat =  Carbon::createFromFormat('Y-m-d H:i:s', $dateTime)->format('m-d-Y H:i:s');
        print("<pre>".print_r($updatedDateFormat, true)."</pre>");
    }

}

The $dateTime variable has the current date format, so create a new variable bind it with Carbon class and access the createFromFormat() method here; you can see two parameters.

The first param is the date format, and the second is also the date-time format; you have to pass your choice of format in format(). The rest will be done automatically. Next, you will see the updated date format in the browser. Easy isn’t it?

So this was it, i believe you would love this quick tutorial and share it with others.