How to set local timezone in laravel

天涯浪子 提交于 2019-12-10 04:22:51

问题


Is there a way to set local timezone in laravel?

In config/app.php

'timezone' => 'UTC',
  • What should be added so that timezone value above uses local timezone?

After some research, stumbled upon the following PHP way of dealing with it:

$userTimezone = Auth::user()->timezone;

date_default_timezone_set($userTimezone);

// and change the configuration so they match

Config::set('app.timezone', $userTimezone)

But, Is there an elegant solution for this other than converting the timezone using the above code.

Cheers


回答1:


Don't do that. Never set the global Laravel timezone to user's timezone. You'll face endless problems.

Choose you application timezone, set the Laravel config to that timezone and never change it.

Instead, when you need to show a date in user's timezone do something like

User::find(1)->foobazed_at->timezone(Auth::user()->timezone);

To control which model columns are automatically converted to Carbon\Carbon instances, add the following method to your model file:

public function getDates()
{
    return array('foobazed_at', static::CREATED_AT, static::UPDATED_AT, static::DELETED_AT);
}


来源:https://stackoverflow.com/questions/31475014/how-to-set-local-timezone-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!