How to set a dynamic timezone in yii2

Published on Author Code Father

How to set a dynamic timezone in yii2? how to set a dynamic timezone for each user in yii2? 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? This is the example how to do it assuming timezone is stored as string in column timezone in userstable. 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:

Comments

comments

Categories Yii

One Response to How to set a dynamic timezone in yii2