web学習日記

プログラミングやweb関係を学んだことを呟くブログ

CakePHP3のタイムゾーンを設定する

f:id:nana205:20190614010140j:plain

CakePHP3でタイムゾーンを設定する

CakePHP3の定義ファイルには初期設定でUTCになっています。 これを日本時間に変更する ちなみにですが、UTC協定世界時と言われる世界の標準時間で日本標準時JSTと表現するようです。

/config/appの値を変更する

'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' => 'nonstandard_port_number',
            'username' => 'user',
            'password' => 'password',
            'database' => 'test',
            'encoding' => 'utf8',
            'timezone' => 'UTC', これをAsia/Tokyo
            'cacheMetadata' => true,

            /**
             * 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'],
        ],

CakePHP3.4の場合/config/bootstrap.phpの値を変更

/config/bootstrap.phpのdate_default_timezone_setの値を変更します。

date_default_timezone_set('Asia/Tokyo');

CakePHP3.6以降のバージョンで仕様が変割りました。

3.6以降の設定は/config/app.php APP_DEFAULT_TIMEZONEを変更するようにします。

'App' => [
        'namespace' => 'App',
        'encoding' => env('APP_ENCODING', 'UTF-8'),
        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
//      'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'UTC'),
        'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'Asia/Tokyo'),

以上で簡単ですが、設定が完了です。お疲れまさでした。