How to handle Time Zones Using Laravel

Sep 26, 2017 Laravel Framework PHP
Laravel Timezone Management | Learn2torials

If you are a Laravel developer and want to know how to manipulate user timezone then this tutorial will help you gain some serious skills regarding timezone management. Consider a scenario where you are given a small project where you have to handle timezones for users all over the world.

Example: you have a small website where you have to remind your users for something according to their location and timezone. You have too many users from different countries. How do you handle this scenario?

Best solution would be to store all the dates/time in UTC format in your database. Add timezone column to your user table when user logs in store their timezone in your user table. When you are ready to set reminder to your user convert utc time to user timezone and you are all set.

Storing Dates to UTC timezone Laravel

First step, open your config/app.php file and make sure timezone is set to 'UTC'. Now, whenever you insert a date in your database all dates will be stored in UTC format. Say that you have a cron job running every minute because our framework timezone is set to utc and all dates are stored in utc in the database.

Your cron checks specific date/time criteria and returns results. Now your task is to convert those datetime to user timezone so that your user sees correct reminder datetime. Followings are some of the functions that will help you with utc time conversion.

How to convert user datetime to UTC time in laravel?

Following function will be used to convert user date to utc in laravel application:

$new_date = Carbon::createFromFormat('Y-m-d H:i', $date, $user->timezone);

How to convert utc date to user timezone in Laravel?

To convert utc date to user date use following code:

$new_date = Carbon::createFromFormat('Y-m-d H:i', $date, 'UTC');

Timezone conversion is very simple with laravel framework as seen in above code. Hope this tutorial will help some developer facing the similar issues with date/time. If you have any suggestions or question or any other questions and need their answers post them below and I will write tutorial about your issues with best answers.

Rate This Article

How to handle user timezones using Laravel carbon? Laravel Utc to user timezone functions.


About Author

Sandip Patel
Sandip Patel

Sandip is passionate about bringing positivity to our communities through story-telling and sharing of real tech blogs.