在 Laravel 中动态更改时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47938368/
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 17:09:01  来源:igfitidea点击:

Change TimeZone dynamically in laravel

phplaravellaravel-5timezonelaravel-5.3

提问by SVM

In my project there is drop-down of time zones(PT,CST etc), when Admin changes the timezone from drop-down the admin panel reflects the timezone from the selected drop down.
How to change Config/app.php "timezone"( Application Timezone) according to the selected option.

在我的项目中有时区下拉列表(PT、CST 等),当管理员从下拉列表更改时区时,管理面板会反映所选下拉列表中的时区。
如何根据选择的选项更改 Config/app.php "timezone"(应用程序时区)。

采纳答案by Phoenix404

You can use Laravel helper function configto set timezone. However, this will affects only the request you will receive.

您可以使用 Laravel 辅助函数config来设置时区。但是,这只会影响您将收到的请求。

config(['app.timezone' => $timezone]);

If your goal is to change once the timezone and run on every request then what about saving the changed timezone in DB or in a file. Then, write a query for DB or read a file in app/config.php and change the value of index timezone in a file.

如果您的目标是更改一次时区并在每个请求上运行,那么将更改的时区保存在数据库或文件中怎么样。然后,写一个查询 DB 或读取 app/config.php 中的文件并更改文件中索引时区的值。

For example (file example):

例如(文件示例):

When you changed the timezone it saves in a file.

当您更改时区时,它会保存在一个文件中。

file_put_contents("path/to/file", $timezone);

And, in app/config.php

而且,在 app/config.php

$timezone= file_get_contents("path/to/file");
return [
 . . .   
    'timezone' => $timezone,
 . . .
]

回答by the_hasanov

you need also call date_default_timezone_set

您还需要调用 date_default_timezone_set

    config(['app.timezone' => $timezone]);
    date_default_timezone_set($timezone);

回答by Alexey Mezenin

If you want to keep a new time zone for all future requests, you need to use a package like larapack/config-writerto be able to save the time zone to the appconfig file.

如果你想为所有未来的请求保留一个新的时区,你需要使用像larapack/config-writer这样的包来将时区保存到app配置文件中。

Another way to handle this is to keep time zone in DB, fetch it in every request and set it with config(['app.timezone' => $timezone])dynamically.

处理此问题的另一种方法是将时区保留在 DB 中,在每个请求中获取它并config(['app.timezone' => $timezone])动态设置它。

回答by Rahul

You can use middlewareto achieve this, whichever routes you will write mention all those applying with that middleware.
You can fetch that data from database and apply it like as follows,

您可以使用它middleware来实现这一点,无论您编写哪条路由,都会提及所有使用该中间件应用的路由。
您可以从数据库中获取该数据并按如下方式应用它,

config('app.timezone', 'your selected timezone')