Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a dynamic timezone in yii2

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?

like image 792
user2707590 Avatar asked Nov 09 '15 13:11

user2707590


1 Answers

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:

  • setTimeZone()
  • date_default_timezone_set() native PHP function
like image 135
arogachev Avatar answered Oct 16 '22 18:10

arogachev