SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

Quick tip on working with timezone in CakePHP 3

In a recent project, we need to allow users to set start and end time of their events and the application is targeted worldwide clients, which leads us to discover some tips on working with timezone in CakePHP 3.

In this post, we share some tips we have learned.

Set Application Timezone to UTC

If you are working on an application that is for a single timezone, then you can happily set the timezone to that timezone.

However if your application is across time zones, to make time calculation and conversions easier, you should set the application's timezone to UTC (If you need a review of UTC, here you go).

We can do that from config/bootstrap.php file:

date_default_timezone_set('UTC');

This will set our application's default timezone to UTC. Any method calls to DateTime instance will take UTC as the timezone. This means all datetime database columns will use UTC-based time.

Convert Inputs to UTC Base

The whole idea of using UTC is to keep times in database in sync, it becomes the single point of truth. When we need to do stuff like calculation and conversions, we can safely assume its base is UTC.

Therefore, when saving time to database, we need to convert users' input which is based on their own timezone to UTC, in order to keep our database as the single point of truth.

CakePHP 3 uses Cake\I18n\Time as the class for handling time. We can use it to do the conversion. For example:

$timeForDatabase = (new Time($userInputTime, 'America/New_York'))->setTimezone('UTC');

Convert Database DataTime to a User's Timezone

When displaying the time from the database to user, we need to convert it back to user's timezone. Otherwise, the user will definitely be confused.

We do it as simply as:

$timeForUser = $timeFromDatabase->setTimezone('America/New_York');

CakePHP 3 ORM will return Cake\I18n\Time instances for DateTime columns. Thus we do not have to instantiate it.

The End

Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.