Lets say my website or web application deals with dates and times and that my users are from all over the world.
How could I create a timezone settings configuration for my users with CakePHP?
Working with Time Helper
First of all we need to work with the time helper that CakePHP offers us. This way will be easier for us.
CakePHP has a configuration called Config.timezone which affects the results showed by the TimeHelper.
We can modify at any moment this configuration using the Configure::write statement:
If we want to allow the user the change the timezone, we first will need to create a form allowing them to choose it.
It can sound very simple but I struggled a lot to find a simple list (not that massive ones which each capital in the world). Also, the list should deal with timezones and not with offset time differences.
We will also need to save the selected timezone in the user’s profile table in the database and in the user session we are working with in order to start working with the new timezone in all the site from now on.
So well, here’s what I did in the profile controller:
And this is my view for that action:
Setting the timezone from the session
We will always need to have the timezone stored in a variable, that way we avoid querying the database every time we want to check the user’s timezone. (as users can change it at any time from the previous form we created)
To set the timezone we just need to add this in the beforeFilter of the controller in which we want to deal with date and times (or in the AppController if you want to affect all the application):
Needless to say that we will also need to store this value in the Session at the login. In that case we want to add a predefined timezone for users who didn’t set any timezone.
Now, everytime we use the timeHelper the result will get affected by our timezone configuration:
Join 2,000+ readers and learn something new every month!
Get notified about new blog posts, tips, tricks, fullPage.js news etc.