PHP: Convert UTC time to local time and vice versa

Updated: January 9, 2024 By: Guest Contributor Post a comment

Overview

Working with time zones can be a critical aspect of developing web applications. This tutorial guides you through converting UTC time to local time and vice versa in PHP, ensuring that you can handle time conversions confidently.

Understanding Timezones in PHP

To work with timezones in PHP, the DateTime class and its associated functions are generally used. They are object-oriented and offer a feature-rich set of options for conversion and formatting.

$now = new DateTime();
$now->setTimezone(new DateTimeZone('UTC'));
echo $now->format('Y-m-d H:i:s');

This snippet creates a new DateTime object for the current time and sets its timezone to UTC, then outputs it in a standard format.

Converting UTC to Local Time

To convert UTC to local time, you must know the local timezone you want to convert to. Use PHP’s DateTimeZone to handle this.

$utcTime     = new DateTime('now', new DateTimeZone('UTC'));
$localTZ     = new DateTimeZone('America/New_York');
$localTime   = clone $utcTime;
$localTime->setTimezone($localTZ);
echo $localTime->format('Y-m-d H:i:s');

In this example, UTC time is converted to New York time. You can replace ‘America/New_York’ with any supported timezone.

Converting Local Time to UTC

Converting from a local time to UTC is similar, by setting the timezone of an existing datetime object to UTC:

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

This takes a New York local time and converts it back to UTC.

Handling Daylight Saving Time

Daylight saving time can add complexity to time conversions. Fortunately, PHP adjusts for DST automatically if an appropriate timezone is specified.

$dt = new DateTime('now', new DateTimeZone('America/New_York'));
echo $dt->format('I') ? 'DST is in effect' : 'DST is not in effect';

By checking the format ‘I’, you can tell whether daylight saving time is currently in effect.

Advanced Time Conversion Techniques

For more complex scenarios, PHP also offers the DateTimeImmutable class and the DateTime::add() and DateTime::sub() methods to manipulate dates and times without affecting the original object.

$dtUTC    = new DateTimeImmutable('now', new DateTimeZone('UTC'));
$dtNY     = $dtUTC->setTimezone(new DateTimeZone('America/New_York'));
$interval = new DateInterval('P1D');
$dtPlusOneDay = $dtNY->add($interval);
echo $dtPlusOneDay->format('Y-m-d H:i:s');

Here, an interval of one day is added to the New York time, displaying the date and time for the next day.

Working with Timestamps

Since UNIX timestamps are always in UTC, converting them to local time just requires setting the timezone after instantiating the DateTime object with the timestamp.

$timestamp = time();
$dt = new DateTime('@'.$timestamp);
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('Y-m-d H:i:s');

The ‘@’ prefix indicates that the following number is a UNIX timestamp.

Time Conversion in User Applications

For user-facing applications, it is often necessary to convert times to the user’s local timezone. You can do this by getting the user’s timezone from their browser, or by letting them select it within your application.

// PHP would receive a timezone string, e.g., $_POST['user_timezone']
$userTimezone = new DateTimeZone('Europe/Berlin');
$utcTime = new DateTime('now', new DateTimeZone('UTC'));
$userTime = clone $utcTime;
$userTime->setTimeZone($userTimezone);
echo $userTime->format('Y-m-d H:i:s');

Handle timezone conversion based on user input with care, always validating and sanitizing the inputted timezone string.

Conclusion

Converting between UTC and local times in PHP is straightforward with the correct use of the DateTime class and its methods. By following the examples above, you can implement time conversion that will automatically account for aspects like daylight saving time. Remember to use PHP’s timezone handling to ensure the accuracy and reliability of time-sensitive operations in your applications.