Configure timezone for PHP

You could get the following warning if timezone is not configured for PHP when using date related function such as date() or date_default_timezone_get().

Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in /path/to/your/script.php on line 3

You can configure timezone for PHP by setting up date.timezone in your configuration file to any of the supported timezones. You can view the list of supported timezones from PHP's official documentation.

The following example sets the timezone to America/Los_Angeles

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = America/Los_Angeles

If you're using PHP 5.1.0 or later, you can you can independently set the timezone for each of your PHP script by calling the date_default_timezone_set function with the timezone as the parameter.

bool date_default_timezone_set ( string $timezone_identifier )

The example below sets the timezone for the rest of the script to America/Los_Angeles.

<?php
date_default_timezone_set('America/Los_Angeles');
?>

Don't forget to restart your webserver after changing the PHO configuration file for the changes to take effect.

Sign up for Object Oriented PHP & MVC and many other great courses on Udemy to learn more.


Written by Mohd Shakir Zakaria. Last updated on 2019-02-12