In this quick tip article, we’ll explain the basics of timezone usage in PHP. Working with timezones is an essential skill for every programmer working with web applications. As PHP has been used mostly for web applications throughout the years, it has fairly simple yet comprehensive timezone support.
Timezones and PHP
Timezones have been supported in PHP since version 4. But what started as a basic implementation of the
date_default_timezone_set() function rapidly evolved in versions 5 and 7 with the introduction of the
DateTimeZoneImmutable is a subclass of
DateTimeZone that makes it possible to create timezones that are immune to modifications. This feature can be very useful in situations where we need to be sure the timezone never changes.
date_default_timezone_set() function sets the default timezone used by all time/date functions on a given script. This function allows setting up the timezone but has very little granularity, forcing us to use the same timezone during the entire execution of the script.
DateTimeZoneImmutable classes brought more control and versatility to the manipulation of timezones. We can now access all sorts of information on the timezone as well as multiple instances of different timezones on the same script.
Using PHP timezones
As noted, there are two main ways of using timezones in PHP.
Timezones on the
date_default_timezone_set() method are always defined in the “Continent/City” or “Continent/Country/City” formats. You can find a complete list of the timezones allowed in PHP here.
This will set the timezone to the timezone passed as an argument. After we’ve set the timezone, we can use functions like
date_default_timezone_get() or any other time-related functions such as
date() to access the new timezone information.
Using the DateTimeZone class
The better way of using timezones in PHP is by using the
DateTimeZone class. This means we have access to more functions to access information and manipulate timezones and we can instantiate multiple instances of the class, which allows us to work with multiple timezones:
<?php $timezone = newDateTimeZone('America/Chicago'); $datetime = new DateTime($date, $timezone); echo $datetime->format('Y-m-d H:i:s');
In this example, we’re creating a new
DateTimeZone object, and passing it to a new instance of
DateTime object will then use the information from the
DateTimeZone object. Finally, we’re using the
format() function to output the date in the format we prefer.
As we’ve seen, working with timezones in PHP is fairly straightforward. Make sure you choose the best way of working for your use case, and PHP has got you covered!