Quick solution

The easiest way to set timezone with PHP is by the date_default_timezone_set() function. This function sets the default timezone used by all date/time functions in PHP.

For example, to set the timezone to Asia/Hong_Kong:

PHP

For a full list of supported timezones, check the official PHP.net Documentation timezone list.

That is how to set timezone with PHP. For more methods and examples, please check the rest of the article.

Set timezone with PHP functions

Set timezone with PHP using date_default_timezone_set

The function syntax:

PHP

Where <strong>$timezoneId</strong> is the string of the timezone to be set. The function will return true if the timezone is valid, else it will return false.

Tips: To get the current timezone that is set in PHP configuration, use date_default_timezone_get function:

PHP

Set timezone with PHP using DateTime

Another method to set timezone with PHP is by object-oriented way using the DateTime object and the DateTimeZone class. The major difference here is the timezone will be set only per created object. Therefore, this method can be used when you want to have multiple variables with multiple timezones, or if the timezone is interchangeable.

For example, we want to have two DateTime object with different timezones:

PHP

Another example is a single DateTime object that can have its timezone updated with DateTime::setTimezone():

PHP

Set timezone with PHP using ini_set

We can also modify timezone configuration dynamically using ini_set function to modify the date.timezone configuration variable:

PHP

Set timezone using server-side configuration

To set the timezone in PHP server-side configuration file – php.ini:

  • In php.ini file, look for the [Date] section;
  • Uncomment the date.timezone configuration line by removing the ; sign at the beginning of the line;
  • Input the desired timezone after the = sign.

Example configuration:

INI

Remember to restart the web server after changing the setting in php.ini.

Final thoughts

These are the methods to set timezone with PHP using multiple methods. We hope these methods are helpful to you, and that they can be utilized in many use cases.