Laravel Time Zones Handling

Why do I care about timezones?

Well, if you are working on app that requires to deal with different countries and their times. Then you should care about handling timezones correctly.

For example, you created an awesome app that deals with users from all around the world. You periodically send them a reminder email with user specified time.

Your app is set to say America/Toronto timezone. One of your user lives in India and you want to remind him at 9AM their time what would you do? Would you remind them at 9AM toronto time?

Well, that sucks because it is 10PM in India when it is 9AM in Toronto. How do I solve this issue?

Storing Dates to UTC timezone Laravel

To handle this scenario you have to first set your laravel app to use UTC time. Now, your user table should have following new column:

  • timezone

When user logs in to your app you should record their timezone correctly and store them in timezone column for logged on user.

If you don't know how to capture correct user timezone you can use third party API that allows to track user geo location. Try following API:

Free Geo IP API

Now, you need to learn two things:

  • How to convert UTC time to User time
  • How to convert User time back to UTC

Convert user time to UTC

Say your user now logs into you web app. Go to your calendar page he picks the date and time he likes to schedule for his reminder.

You take that user time and then covert to UTC time and save it in your database. Later your cron job picks up that reminder and send notification to user.

To convert user time to UTC use following laravel code in your controller method:

# convert user date provided date string to user date
$user_date = date('Y-m-d H:i:s', strtotime($date_string));

# convert user date to utc date
$utc_date = Carbon::createFromFormat('Y-m-d H:i', $user_date, $user->timezone);
$utc_date->setTimezone('UTC');

# check the utc date
dd($utc_date);

Convert UTC time to User time

To convert utc time back to user time you need following logic in your laravel controller:

# using utc date convert date to user date
$user_date = Carbon::createFromFormat('Y-m-d H:i', $utc_date, 'UTC');
$user_date->setTimezone($user->timezone);

# check the user date
dd($user_date);

That is it, once you know how to convert date back end forth from utc to user date you will be able to handle user times efficiently.