3 Easy methods to change date format in Laravel 6,7 and 8

Here we are going to look at how to change date format in Laravel using the following methods,

Working with date and time is a usual things in all types of applications. Many times we need to format a date object as per our requirements. Lets check out few simple methods to change date format in Laravel.

Methods to change date format

date() method

The date() method returns the current date and time as a date object. However, you can use the date function on any date and format as you need it. For example, use the ‘d/m/Y’ string to the date method alongside the strtotime function on the specific date.

$date = "2023-02-06";
date('d/m/Y', strtotime($date));

The strtotime() function will change the any date from string to date and in your specified format.

Carbon parse() method

Carbon is a strong PHP API inherited from the PHP DateTime class. You can use it to format a given date to any other type.

use Carbon\Carbon;
$date = "2023-02-06";
Carbon::parse($date)->format('d/m/Y');

The format() method here parses a given date to the specified format, i.e. ‘d/m/Y’, as shown above.

Carbon createFromFormat() method

Carbon PHP API also provides you with a createFromFormat() method that will help create a date using the provided format.

use Carbon\Carbon;
$date = "2023-02-06";
Carbon::createFromFormat('Y-m-d', $date)->format('d/m/Y');

The createFromFormat() method specifies the requested date format, and the format() method will then specify what the converted date format should be.

Output

Using the format specified in each of the function, you will get the output date as: 06/02/2023.

Leave a Comment