CakePHP | timezoneの変更

CakePHPをインストールすると、timezoneがデフォルト設定の「UTC」になっています。
この状態で、DBを登録、更新すると、日本時間よりも9時間ずれます。

これを対処するには、CakePHPの設定ファイルを2か所修正する必要があります。

本記事では、timezoneの変更方法を記載しています。

config/app.php

timezoneの項目を、UTC → +09:00 に変更します。

 

'Datasources' => [
        'default' => [
            'className' => Connection::class,
            'driver' => Mysql::class,
            'persistent' => false,
            'host' => 'hoge_server',
            /*
             * 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
             */
            'username' => 'hoge',
            'password' => 'xyz',
            'database' => 'hoge_db',
            /*
             * You do not need to set this flag to use full utf-8 encoding (internal default since CakePHP 3.6).
             */
            //'timezone' => 'UTC',
            'timezone' => '+09:00',
            'flags' => [],
            'cacheMetadata' => true,
            'log' => false,

            /**
             * Set identifier quoting to true if you are using reserved words or
             * special characters in your table or column names. Enabling this
             * setting will result in queries built using the Query Builder having
             * identifiers quoted when creating SQL. It should be noted that this
             * decreases performance because each query needs to be traversed and
             * manipulated before being executed.
             */
            'quoteIdentifiers' => false,

            /**
             * During development, if using MySQL < 5.6, uncommenting the
             * following line could boost the speed at which schema metadata is
             * fetched from the database. It can also be set directly with the
             * mysql configuration directive 'innodb_stats_on_metadata = 0'
             * which is the recommended value in production environments
             */
            //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],

            'url' => env('DATABASE_URL', null),
        ],

config/bootstrap.php

date_default_timezone_set(Configure::read('App.defaultTimezone'));
↓
date_default_timezone_set('Asia/Tokyo');

スポンサーリンク