In this article, I am going to cover how you can set the timezone or change it in laravel. I will cover both manual and dynamic ways of setting timezone in laravel.
I will cover in the following order:
1. Set the timezone manually in laravel
2. Set the timezone dynamically in laravel
If you are using laravel 9, you can check this post on how to set timezone in laravel 9.
I have also created a video on this topic, so if you don’t want to follow the article, you can watch the video covering the same topic.
Let’s get started.
1. Setting Timezone Manually in files
In this section, first I will share with you the manual way to set the timezone in the config/app.php file itself.
Step 1: Open Config/app.php file
In this method, we are setting the UTC timezone, which means the timezone will get changed for the entire application.
In the laravel project open the file
config/app.php, you will notice the
'timezone' => 'UTC', by default, timezone is set to UTC.
Step 2: Replace UTC with your timezone
Now you will replace UTC with your timezone.
If you don’t know what is code for your timezone, you can check the complete list here of timezones available in PHP.
I will be using
Europe/Paris as my timezone. So the file will look like this.
Step 3: Clear the Config Cache
Run the following command in the terminal to clear the cache:
php artisan config:clear
Step 4: Print in controller or view
$current_date_time=Carbon\Carbon:now(); echo $current_date_time;
That’s all you need to do 🙂
Bonus Tip for setting timezone manually in laravel:
Now if your developer’s localhost timezone is different from the timezone you needed on the production. Then you need to change this field again and again when you deploy the application.
Good Solution is that you put the that timezone in the
env file. Lets do that.
- You create the variable in
2. Then in
config/app.php, you will change timezone to following
'timezone' => env('APP_TIMEZONE','UTC'),
3. Clear the Config Cache
php artisan config:clear
env file will look like this:
config/app.php will look like this
2. Setting Timezone Dynamically:
There can be cases where we don’t have to change the whole laravel application timezone but for a particular task only. Here is how you will do.
Step 1: Calling the php timezone function
In this method, you just need to call the PHP time zone function
date_default_timezone_set in your controller or view.
date_default_timezone_set('Europe/Paris') $current_date_time=Carbon\Carbon:now(); echo $current_date_time;
Note the timezone will only be affected for the current request.
Step 2: Clear cache if it doesn’t work
For some reason, if it’s not get affected, try to clear the cache.
php artisan cache:clear php artisan config:clear
Hope you have learned how to set the timezone in laravel both manual and dynamic ways. Also the bonus tip as well.
Feel free to comment and share your thoughts.
Keep Learning Keep Working 🙂
See you in the next post.