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
:
date_default_timezone_set('Asia/Hong_Kong');
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:
date_default_timezone_set(string $timezoneId): bool
Where $timezoneId
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:
echo date_default_timezone_get(); // returns the configured timezone
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:
$dateHongKong = new DateTime('2023-01-01', new DateTimeZone('Asia/Hong_Kong'));
echo $dateHongKong->format('Y-m-d H:i:sP'); // 2023-01-01 00:00:00+08:00
$dateJapan = new DateTime('2023-01-01', new DateTimeZone('Asia/Tokyo'));
echo $dateJapan->format('Y-m-d H:i:sP'); // 2023-01-01 00:00:00+09:00
Another example is a single DateTime
object that can have its timezone updated with DateTime::setTimezone()
:
// Hong Kong timezone
$date = new DateTime('2023-01-01', new DateTimeZone('Asia/Hong_Kong'));
// Change to Japan timezone
$date->setTimeZone(new DateTimeZone('Asia/Tokyo'));
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:
ini_set('date.timezone', 'America/New_York');
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:
...
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Asia/Japan
...
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.