SyntaxStudy
Sign Up
PHP Timezone Handling
PHP Intermediate 8 min read

Timezone Handling

Incorrect timezone configuration is one of the most common sources of date/time bugs in PHP applications. PHP stores datetimes internally in UTC and converts for display.

  • Set the default timezone with date_default_timezone_set() or the date.timezone ini setting.
  • Pass a DateTimeZone object when constructing DateTime objects to be explicit.
  • Convert between timezones with setTimezone().
Example
<?php
// Set application-wide default (do this once at bootstrap)
date_default_timezone_set('UTC');

// Create with explicit timezone
$tz_ny  = new DateTimeZone('America/New_York');
$tz_tyo = new DateTimeZone('Asia/Tokyo');

$now_utc = new DateTimeImmutable('now', new DateTimeZone('UTC'));
echo $now_utc->format('Y-m-d H:i:s T'); // 2024-07-15 14:00:00 UTC

// Convert to New York time
$now_ny = $now_utc->setTimezone($tz_ny);
echo $now_ny->format('Y-m-d H:i:s T'); // 2024-07-15 10:00:00 EDT

// Convert to Tokyo time
$now_tyo = $now_utc->setTimezone($tz_tyo);
echo $now_tyo->format('Y-m-d H:i:s T'); // 2024-07-16 23:00:00 JST

// List all timezones in a region
$zones = DateTimeZone::listIdentifiers(DateTimeZone::AMERICA);
foreach (array_slice($zones, 0, 5) as $z) {
    echo $z . "
";
}

// Get UTC offset in hours
$offset = $tz_ny->getOffset(new DateTime()) / 3600;
echo "NY offset: $offset hours";
Pro Tip

Tip: Always store datetimes in UTC in your database and convert to local time only for display. This makes sorting, comparing, and DST transitions trivial.