设置时区不会改变CakePHP 3.x中的显示时间

时间:2015-05-04 10:05:19

标签: cakephp timezone cakephp-3.0

我正在使用CakePHP 3.x并遇到小时问题。

我的数据库(MySQL)中有正确的小时数。 当我的应用程序显示这些时间时,我有几个小时的UTC而不是我的记录。 换句话说,我的数据库中记录了10:00,而我的网站上显示的是08:00

根据食谱,我试图改变

date_default_timezone_set('UTC');

date_default_timezone_set('Europe/Paris');
config / bootstrap.php

中的

但我仍然有时间在UTC。 也许我错过了什么?

提前致谢

3 个答案:

答案 0 :(得分:9)

我找到了这个解决方案:

config / app.php 中,将timezone数组中的Datasources保留为空:

'Datasources' => [
    'default' => [
        /* previous code */
        'timezone' => '',
        /* next code */
    ],
]

我不知道它是否正确但是有效

答案 1 :(得分:8)

对于CakePHP 3.0,在bootstrap.php第95-99行中设置默认时区

/**
 * Set server timezone to UTC. You can change it to another timezone of your
 * choice but using UTC makes time calculations / conversions easier.
 */
date_default_timezone_set('Asia/Karachi');

List of PHP Timezones.

要使其与数据库保持同步,还要在app.php第216-238行中设置数据库时区

'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        /**
         * CakePHP will use the default DB port based on the driver selected
         * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
         * the following line and set the port accordingly
         */
        //'port' => 'non_standard_port_number',
        'username' => 'root',
        'password' => '',
        'database' => 'invoicing',
        'encoding' => 'utf8',
        'timezone' => '+8:00', // It can be UTC or "+10:00" or "-4:00"
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,

MySQL Reference

答案 2 :(得分:2)

date_default_timezone_set('Europe/Paris');用于在时区中显示日期('Ym-d')或类似信息,或者在保存信息时会影响,并将存储在巴黎时区而不是UTC中,仅更改它影响信息的保存方式。请点击此处了解更多信息:

http://php.net/manual/en/function.date-default-timezone-set.php

如果您想要更改每个用户在不同时区显示信息的方式,请始终在一个时区保存信息,请查看以下内容:

http://book.cakephp.org/3.0/en/views/helpers/time.html#using-the-helper

echo $this->Time->format( $post->created, \IntlDateFormatter::FULL, null, $user->time_zone );