Awesome CakePHP 3
This article is part of series in Awesome CakePHP 3:
- Generating PDFs from html and snappy in CakePHP 3
- Real time notifications using Pusher in CakePHP 3
- Building Custom Search Engine with Algolia and CakePHP 3
- Sending Email with SES in CakePHP 3
- Installing WordPress in a CakePHP application
- Manually reconnect MySQL in CakePHP 3
- Quick tip on working with timezone in CakePHP 3
- How to integrate Facebook login with 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.
Table Of Content
- Set Application Timezone to UTC
- Convert Inputs to UTC Base
- Convert Database DataTime to a User's Timezone
- The End
1. 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:
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.
2. 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:
3. 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:
CakePHP 3 ORM will return Cake\I18n\Time instances for DateTime columns. Thus we do not have to instantiate it.
4. 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.