laravel 如何在laravel中设置本地时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31475014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:57:44  来源:igfitidea点击:

How to set local timezone in laravel

phplaravellaravel-4timezonelaravel-5

提问by Roy M J

Is there a way to set local timezone in laravel?

有没有办法在 Laravel 中设置本地时区?

In config/app.php

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:

经过一番研究,偶然发现了以下PHP处理方式:

$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

干杯

回答by Javi Stolz

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

不要那样做。永远不要将全局 Laravel 时区设置为用户的时区。你会面临无穷无尽的问题。

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

选择您的应用程序时区,将 Laravel 配置设置为该时区并且永远不要更改它。

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\Carboninstances, add the following method to your model file:

要控制哪些模型列自动转换为Carbon\Carbon实例,请将以下方法添加到您的模型文件中:

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