在Laravel 5中基于系统时区配置Laravel时区

时间:2018-11-26 19:02:21

标签: php laravel laravel-5 centos timezone

我试图根据我在CentOS VM上的系统时间在config/app.php上设置时区配置。

'timezone' => 'America/New_York',

我尝试在config/app.php顶部添加以下几行代码

// Try #1
// $timeZone = shell_exec("date +\"%Z %z\" | awk '{print $1}'");
// dd($timeZone);  I got "EST\n"

// Try #2
// session_start();
// $timezone = $_SESSION['time'];
// dd($timeZone);

// Try #3
// $timezone = date_default_timezone_get()
// dd($timeZone);

以上这些似乎都不起作用。

如何进一步调试呢?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

$now = new DateTime();
$tz = $now->getTimezone();
$tz = $tz->getName();

如果上述方法无效,建议您查看Carbon

您的config/app.php文件将类似于:

<?php
# include Carbon
use Carbon\Carbon;

return [
    . 
    .
    . 
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => Carbon::createFromTimestamp(0, 'America/New_York')->timezone->getName(),
    .
    . 
    .

];

要测试以上内容的输出,请不要在dd()内死转储app/config.php,您可以创建一条新路径:

Route::get('/test-timezone', function() {
    dd(\Config::get('app.timezone'));
});

确保清除缓存以查看更改:php artisan config:cache