Does anyone know how to set a dynamic timezone for each user? If the timezone is stored in database, how do i get it from db and set it at runtime so that i dont need to set it everytime in my codes?
Asked
Active
Viewed 4,093 times
1 Answers
11
This is an example how to do it assuming timezone is stored as string in column timezone
in users
table. Add this to your application config:
'on beforeRequest' => function () {
$user = Yii::$app->user->identity;
if ($user && $user->timezone) {
Yii::$app->setTimeZone($user->timezone);
}
},
This code will run before request and set timezone depending on specific user. Of course you can move it to separate class and call it from here.
Official docs:

Salem Ouerdani
- 7,596
- 3
- 40
- 52

arogachev
- 33,150
- 7
- 114
- 117
-
1Thanks. I figured it out since yesterday though. Hope it helps other users – user2707590 Nov 10 '15 at 15:32
-
@user2707590 You can also accept an answer in this case. – arogachev Nov 11 '15 at 03:09
-
`on beforeRequest` is triggered just after `yii\base\Application::bootstrap`. isn't that too early to expect a user identity to be loaded? – Salem Ouerdani Jan 03 '18 at 03:26