简体   繁体   中英

Configuring the Laravel timezone base on the system timezone in Laravel 5

I'm trying to set the timezone configuration on config/app.php base on my the system time on CentOS VM automatically.

'timezone' => 'America/New_York',

I've tried added these few lines of code on top of 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);

None of these above seem to work.

How would one go about debugging this further?

You can try this:

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

If the above doesn't work I suggest you to look at Carbon ;

Your config/app.php file will be something like:

<?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(),
    .
    . 
    .

];

To test the output of the above do not die dump dd() inside your app/config.php you can make a new route:

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

Make sure to clear the cache to see the changes: php artisan config:cache

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM