How to Set Timezone in Laravel?

By Hardik Savani September 14, 2022 Category : Laravel

Hi Developer,

I am going to show you an example of how to set timezone in laravel. you will learn how to set timezone in carbon laravel. you will learn laravel set timezone globally. We will use set timezone in laravel.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

There are several ways to set timezone in the laravel application. I will give you the following three examples to set timezone in the laravel app.

1) Laravel Set Timezone in Config File

2) Laravel Set Timezone in .env File

3) Laravel Set Timezone Dynamically

So, Without further ado, let's see the below example one by one.

Example 1: Laravel Set Timezone in Config File

In this solution, you need to go in app.php config file and change timezone. I changed UTC into Asia/Kolkata as like bellow:

config/app.php

<?php

use Illuminate\Support\Facades\Facade;

return [

.....

.....

'timezone' => 'Asia/Kolkata',

.....

.....

]

Controller File Code:

Then, you can get now time using Carbon as like below code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Carbon\Carbon;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$now = Carbon::now();

dd($now);

}

}

Example 2: Laravel Set Timezone in .env File

In this solution, you need to add APP_TIMEZONE variable in .env file and use it on app.php config file and change timezone. I changed UTC into Asia/Kolkata as like bellow:

.env

APP_TIMEZONE='Asia/Kolkata'

config/app.php

<?php

use Illuminate\Support\Facades\Facade;

return [

.....

.....

'timezone' => env('APP_TIMEZONE','UTC'),

.....

.....

]

Controller File Code:

Then, you can get now time using Carbon as like below code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Carbon\Carbon;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$now = Carbon::now();

dd($now);

}

}

Example 3: Laravel Set Timezone Dynamically

In this solution, we can set Dynamically timezone using date_default_timezone_set() function. so let's see below code.

Controller File Code:

Then, you can get now time using Carbon as like below code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Carbon\Carbon;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

date_default_timezone_set('Asia/Kolkata');

$now = Carbon::now();

dd($now);

}

}

I hope it can help you...

Tags :