8

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?

user2707590
  • 1,066
  • 1
  • 14
  • 28

1 Answers1

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