How to Change Date Format in Laravel 7/6? (ok)

https://www.itsolutionstuff.com/post/how-to-change-date-format-in-laravel-6example.html

C:\xampp\htdocs\reset\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use Carbon\Carbon;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
  return view('welcome');
});
Route::get('/test', function () {
  $date = date('Y-m-d H:i:s');
  echo $date;
  echo "<br/>";
  $newDate1 = Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d-m-Y');
  echo $newDate1; // "22-02-2020"
  echo "<br/>";
  $newDate2 = Carbon::createFromFormat('d-m-Y', $newDate1)->format('m/d/Y');
  echo $newDate2; // "02/22/2020"
  echo "<br/>";
  $newDate3 = Carbon::createFromFormat('m/d/Y', $newDate2)->format('Y-m-d');
  echo $newDate3; // "2020-02-22"
  echo "<br/>";
  $newDate4 = Carbon::createFromFormat('Y-m-d', $newDate3)->format('d/m/Y');
  echo $newDate4; // "22/02/2020"
});

How to Change Date Format in Laravel 7/6?

Sometimes you require to change date format in your laravel app. we have to use Carbon class for change format in laravel, because it provide many date function for like change date formate, count diffrence between two dates in days etc. So, Basically i am going to show you change date format using Carbon. we will use createFromFormat() and format(), createFromFormat() will take two argument first give format of date and second one date and format() take one argument give formate as you want. you can see bellow examples:

Example 1

public function create(){    $date = date('Y-m-d H:i:s');    $newDate = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)                    ->format('d-m-Y');      dd($newDate);}

Output

"22-02-2020"

Example 2: Y-m-d to m/d/Y

public function create(){    $date = "2020-02-22";    $newDate = \Carbon\Carbon::createFromFormat('Y-m-d', $date)                    ->format('m/d/Y');    dd($newDate);}

Output

"02/22/2020"

Example 3: m/d/Y to Y-m-d

public function create(){    $date = "02/22/2020";    $newDate = \Carbon\Carbon::createFromFormat('m/d/Y', $date)                    ->format('Y-m-d');    dd($newDate);}

Output

"2020-02-22"

Example 3: Y-m-d to d/m/Y

public function create(){    $date = "2020-02-22";    $newDate = \Carbon\Carbon::createFromFormat('Y-m-d', $date)                    ->format('d/m/Y');    dd($newDate);}

Output

Read Also: Laravel 8/7 Notification Tutorial | Create Notification with Laravel 8/7

"22/02/2020"

I hope it can help you...

Last updated