Timezone in Yii2

2019-08-25 09:50发布

问题:

My computer time zone 'Asia/Tashkent'. And I set Yii2 time zone to 'Asia/Tashkent' too in config. But Yii2 is still displaying time incorrectly. I am wondering what I have missed?

$time = date("Y-m-d H:i:s", time()); 
echo $time;  // 2018-03-07 14:10:57
echo Yii::$app->formatter->asTime($time, 'medium'); // 7:10:57 PM
echo Yii::$app->formatter->asDate($time, 'medium'); // Mar 7, 2018
echo date_default_timezone_get(); // Asia/Tashkent

回答1:

If you are giving asTime() string date formatter assumes it's in default timezone which by default in Yii 2 is UTC.

If you want this to be the same as the output of PHP date() change the default timezone in Yii to yours. For example in the configuration:

'components' => [
    'formatter' => [
        'class'           => 'yii\i18n\Formatter',
        'defaultTimeZone' => 'Asia/Tashkent',
    ],
],


标签: php yii2