Quick Tip: How To Manage Timezones in PHP

Share this article

Quick Tip: How To Manage Timezones in PHP
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.

Key Takeaways

  1. PHP’s Evolution in Timezone Management: Since PHP 4, timezone support has evolved significantly, with PHP 5 and 7 introducing the DateTimeZone and DateTimeZoneImmutable classes, enhancing control and versatility in managing timezones within applications.
  2. Two Main Methods for Handling Timezones: PHP offers two primary ways to work with timezones: through the date_default_timezone_set() function for a script-wide setting and the DateTimeZone class for more granular control, allowing access to a plethora of timezone-related information and the ability to handle multiple timezones simultaneously.
  3. Choosing the Right Approach for Timezone Manipulation: The article underscores the importance of selecting the most appropriate method for timezone manipulation in PHP, whether it’s setting a global default timezone for the script or utilizing the DateTimeZone class for more complex scenarios, to ensure efficient and error-free timezone handling in web applications.

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 DateTimeZone and DateTimeZoneImmutable classes. 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. The 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. The DateTimeZone and 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.

Using date_default_timezone_set()

<?php
    date_default_timezone_set('America/LosAngeles');
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. The 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.

Conclusion

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!

Frequently Asked Questions (FAQs) about PHP Timezones

How Can I Set a Default Timezone in PHP?

In PHP, you can set a default timezone using the date_default_timezone_set() function. This function requires a single parameter, which is the string identifier of the timezone you want to set. For example, to set the timezone to Eastern Standard Time, you would use the following code:

date_default_timezone_set('America/New_York');

This will set the default timezone for all date/time functions in the script that follows.

How Can I Get the Current Timezone in PHP?

You can get the current timezone in PHP using the date_default_timezone_get() function. This function returns a string that represents the current timezone. Here’s an example:

echo date_default_timezone_get();

This will output the current timezone, such as ‘America/New_York’ if the timezone was previously set to Eastern Standard Time.

How Can I List All Timezones Available in PHP?

PHP provides the DateTimeZone::listIdentifiers() function, which returns an indexed array containing all timezone identifiers. Here’s how you can use it:

$timezones = DateTimeZone::listIdentifiers();
print_r($timezones);

This will output an array of all available timezone identifiers.

How Can I Convert Time Between Different Timezones in PHP?

PHP provides the DateTime and DateTimeZone classes which can be used to convert time between different timezones. Here’s an example:

$date = new DateTime('now', new DateTimeZone('America/New_York'));
$date->setTimezone(new DateTimeZone('Europe/London'));
echo $date->format('Y-m-d H:i:s');

This will output the current time in London, regardless of the server’s default timezone.

How Can I Handle Daylight Saving Time (DST) in PHP?

PHP’s DateTime and DateTimeZone classes automatically handle Daylight Saving Time (DST). When you create a DateTime object and set its timezone, PHP will adjust the time according to the DST rules for that timezone. Here’s an example:

$date = new DateTime('now', new DateTimeZone('America/New_York'));
echo $date->format('Y-m-d H:i:s');

This will output the current time in New York, taking into account DST if it is currently in effect.

How Can I Format Dates and Times in PHP?

PHP provides the date() function, which formats a local date and time. It requires a format string and an optional Unix timestamp. If no timestamp is given, the current time is used. Here’s an example:

echo date('Y-m-d H:i:s');

This will output the current date and time in the format ‘YYYY-MM-DD HH:MM:SS’.

How Can I Parse Dates and Times from Strings in PHP?

PHP provides the strtotime() function, which parses a textual datetime into a Unix timestamp. Here’s an example:

$timestamp = strtotime('2022-01-01 12:00:00');
echo date('Y-m-d H:i:s', $timestamp);

This will output ‘2022-01-01 12:00:00’.

How Can I Compare Dates and Times in PHP?

PHP provides several ways to compare dates and times. One common method is to convert the dates/times to Unix timestamps using strtotime() and then compare the timestamps. Here’s an example:

$date1 = strtotime('2022-01-01 12:00:00');
$date2 = strtotime('2022-01-02 12:00:00');
if ($date1 < $date2) {
echo 'Date1 is earlier than Date2';
} else {
echo 'Date1 is later than Date2';
}

This will output ‘Date1 is earlier than Date2’.

How Can I Add or Subtract Time in PHP?

PHP provides the strtotime() function, which can also be used to add or subtract time. Here’s an example:

$now = time();
$nextWeek = strtotime('+1 week', $now);
echo date('Y-m-d H:i:s', $nextWeek);

This will output the date and time one week from now.

How Can I Handle Timezones in MySQL Using PHP?

When working with MySQL, you can set the timezone for the current session using the SET time_zone command. Here’s how you can do it in PHP:

$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$pdo->exec("SET time_zone='+00:00'");

This will set the timezone to UTC for the current MySQL session.

Claudio RibeiroClaudio Ribeiro
View Author

Cláudio Ribeiro is a software developer, traveler, and writer from Lisbon. He's the author of the book An IDE Called Vim. When he is not developing some cool feature at Kununu he is probably backpacking somewhere in the world or messing with some obscure framework.

PHP Quick Tipstimezones
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week