Timezones

Su Subhalakshmi Chandran Updated 05 Nov 2026
8 min read ·Lesson 240 of 248

Why Time Zones Matter

In simple terms: The same moment has different local times around the world. A live class that starts at 7:00 PM in Chennai starts at 9:30 AM in New York and 2:30 PM in London. An application with users, servers, or partners in different places must know which clock a time refers to.

Technically: A time zone is a region that uses the same rules for converting between UTC (Coordinated Universal Time, the global reference time) and local time. The rules include a UTC offset (India: +05:30) and, in many regions, daylight saving time (DST) changes during the year. PHP uses the IANA time zone database, identified by names such as Asia/Kolkata, Europe/London, and America/New_York.

Common Problems Without Time Zone Awareness

  • An order placed at 11:30 PM in India appears under the wrong date in reports generated on a UTC server.
  • A meeting invitation shows the wrong time to participants in other countries.
  • A "24-hour offer" ends an hour early or late in a DST region.
  • Dates stored by servers in different regions cannot be compared.

Key Concepts

TermMeaning
UTCThe global reference time, with no offset and no daylight saving time
OffsetDifference from UTC at a given moment, such as +05:30 or -04:00
Time zone identifierIANA name such as Asia/Kolkata; contains all historical and future rules
AbbreviationShort label such as IST or EDT — ambiguous (IST also means Irish and Israel Standard Time)
DSTSeasonal clock change used in many regions (not in India)

Always use identifiers, not offsets or abbreviations, to describe where a user is. An offset like -05:00 is correct for New York only part of the year; America/New_York is correct all year.


Setting PHP's Default Time Zone

<?php
date_default_timezone_set('Asia/Kolkata');

echo date_default_timezone_get() . "\n";
echo date('Y-m-d H:i T', 1792054800) . "\n";

Output

Asia/Kolkata
2026-10-15 14:30 IST

The default time zone is used by date(), mktime(), strtotime(), and by date objects created without an explicit time zone. Set it once — in php.ini (date.timezone = Asia/Kolkata or UTC) or at application startup — so results never depend on the server's configuration.

Many applications set the default to UTC on servers and convert to the user's time zone only for display.


DateTimeZone and Converting Between Zones

Creating a Date in a Specific Time Zone

<?php
$chennai = new DateTimeZone('Asia/Kolkata');

$classStart = new DateTimeImmutable('2026-10-15 19:00', $chennai);

echo $classStart->format('Y-m-d H:i T P') . "\n";
echo $classStart->getTimestamp() . "\n";

Output

2026-10-15 19:00 IST +05:30
1792071000

The date is interpreted as 7:00 PM in India. The timestamp is the universal moment, the same everywhere.

Showing the Same Moment in Other Zones

setTimezone() changes how a moment is displayed; the moment itself (the timestamp) stays the same:

<?php
$classStart = new DateTimeImmutable('2026-10-15 19:00', new DateTimeZone('Asia/Kolkata'));

$zones = ['Asia/Kolkata', 'UTC', 'Europe/London', 'America/New_York', 'Asia/Tokyo', 'Australia/Sydney'];

foreach ($zones as $zone) {
    $local = $classStart->setTimezone(new DateTimeZone($zone));
    echo str_pad($zone, 18) . $local->format('D, d M Y H:i T') . "\n";
}

Output

Asia/Kolkata      Thu, 15 Oct 2026 19:00 IST
UTC               Thu, 15 Oct 2026 13:30 UTC
Europe/London     Thu, 15 Oct 2026 14:30 BST
America/New_York  Thu, 15 Oct 2026 09:30 EDT
Asia/Tokyo        Thu, 15 Oct 2026 22:30 JST
Australia/Sydney  Fri, 16 Oct 2026 00:30 AEDT

What This Shows

  • Every line is the same instant; only the local representation differs.
  • In Sydney, the class starts on Friday — the local date can differ from yours.
  • In mid-October 2026, London (BST, +01:00), New York (EDT, −04:00), and Sydney (AEDT, +11:00) are on daylight saving time. A few weeks later, London and New York switch back and their offsets change, while India's offset stays +05:30 all year.

setTimezone() on DateTimeImmutable returns a new object; the original keeps its time zone.

Offsets and Available Zones

<?php
$india = new DateTimeZone('Asia/Kolkata');
echo $india->getOffset(new DateTimeImmutable('2026-10-15')) . " seconds\n";

print_r(DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, 'IN'));

Output

19800 seconds
Array
(
    [0] => Asia/Kolkata
)

getOffset() returns the offset in seconds for a given moment (19800 seconds = 5 hours 30 minutes). Because offsets can change with DST, it needs a date. listIdentifiers() lists valid identifiers — useful for building a time zone selection list for user profiles.


Daylight Saving Time: Calendar Days vs Elapsed Hours

In DST regions, "1 day later" and "24 hours later" are not always the same:

<?php
$newYork = new DateTimeZone('America/New_York');
$saturdayNoon = new DateTimeImmutable('2026-03-07 12:00', $newYork);

echo $saturdayNoon->modify('+1 day')->format('Y-m-d H:i T') . "\n";
echo $saturdayNoon->add(new DateInterval('PT24H'))->format('Y-m-d H:i T') . "\n";

Output (PHP 8.1 and newer)

2026-03-08 12:00 EDT
2026-03-08 13:00 EDT

On 8 March 2026, clocks in New York jump forward one hour, so that Sunday has only 23 hours:

  • +1 day means "the same wall-clock time on the next calendar day" → 12:00.
  • PT24H means "exactly 24 elapsed hours later" → 13:00.

Choose deliberately: reminders and recurring events usually follow the calendar (+1 day), while expiry periods and timeouts usually follow elapsed time (PT24H or timestamps).


Storing and Displaying Times

A robust strategy used by most applications:

User input (local time) ──convert──► UTC ──store──► Database
Database (UTC) ──convert──► User's time zone ──format──► Display
<?php
function localToUtc(string $localDateTime, string $timeZone): string
{
    return (new DateTimeImmutable($localDateTime, new DateTimeZone($timeZone)))
        ->setTimezone(new DateTimeZone('UTC'))
        ->format('Y-m-d H:i:s');
}

function utcToLocal(string $utcDateTime, string $timeZone, string $format = 'd M Y, g:i A T'): string
{
    return (new DateTimeImmutable($utcDateTime, new DateTimeZone('UTC')))
        ->setTimezone(new DateTimeZone($timeZone))
        ->format($format);
}

$stored = localToUtc('2026-10-15 19:00', 'Asia/Kolkata');

echo "Stored in database: $stored\n";
echo "Shown to a user in Chennai: " . utcToLocal($stored, 'Asia/Kolkata') . "\n";
echo "Shown to a user in New York: " . utcToLocal($stored, 'America/New_York') . "\n";

Output

Stored in database: 2026-10-15 13:30:00
Shown to a user in Chennai: 15 Oct 2026, 7:00 PM IST
Shown to a user in New York: 15 Oct 2026, 9:30 AM EDT

Why UTC Storage Works

  1. Every stored value refers to the same reference clock, so values from different users and servers can be compared and sorted directly.
  2. UTC has no DST changes, so there are no missing or repeated hours in stored data.
  3. Display is a separate step that can use each user's preferred time zone.

Where the User's Time Zone Comes From

  • A profile setting (select from DateTimeZone::listIdentifiers()).
  • The browser: JavaScript's Intl.DateTimeFormat().resolvedOptions().timeZone returns an identifier such as Asia/Kolkata, which can be sent with a form or stored in a cookie.
  • A sensible default for your audience (for an Indian platform, Asia/Kolkata).

Validate any submitted identifier with in_array($tz, DateTimeZone::listIdentifiers(), true) before using it.

Databases

  • In MySQL, DATETIME stores the value exactly as given (no time zone), so store UTC in it consistently. TIMESTAMP converts between the connection's time zone and UTC automatically, which can surprise you if connections use different settings; it is also limited to dates up to 2038.
  • PostgreSQL offers timestamptz, which stores an absolute moment and converts on output.

Practical Example: Is the Store Open?

<?php
function isOpen(DateTimeInterface $moment, string $storeTimeZone, int $openHour, int $closeHour): bool
{
    $local = DateTimeImmutable::createFromInterface($moment)->setTimezone(new DateTimeZone($storeTimeZone));
    $hour = (int) $local->format('G');
    $isSunday = $local->format('N') === '7';

    return !$isSunday && $hour >= $openHour && $hour < $closeHour;
}

$checks = [
    '2026-10-15 05:00:00',   // UTC
    '2026-10-15 15:00:00',
    '2026-10-18 06:00:00',
];

foreach ($checks as $utc) {
    $moment = new DateTimeImmutable($utc, new DateTimeZone('UTC'));
    $local = $moment->setTimezone(new DateTimeZone('Asia/Kolkata'));
    printf("%s UTC = %s → %s\n",
        $moment->format('D H:i'),
        $local->format('D H:i T'),
        isOpen($moment, 'Asia/Kolkata', 10, 20) ? 'open' : 'closed'
    );
}

Output

Thu 05:00 UTC = Thu 10:30 IST → open
Thu 15:00 UTC = Thu 20:30 IST → closed
Sun 06:00 UTC = Sun 11:30 IST → closed

Step-by-Step Explanation

  1. The function receives any moment (here created in UTC, as it might come from a server clock or database) and converts it to the store's time zone before checking opening hours.
  2. createFromInterface() accepts both DateTime and DateTimeImmutable and returns an immutable copy, so the caller's object is never modified.
  3. The store is open from 10:00 to 20:00 local time, Monday to Saturday.
  4. 15:00 UTC is 8:30 PM in India — after closing — even though "15:00" looks like business hours. Checking the UTC hour directly would have given the wrong answer.

Common Mistakes

Relying on the Server's Time Zone

Effect: Results change when the application moves to another server or cloud region.

Fix: Configure the time zone explicitly and pass DateTimeZone objects.

Storing Local Times Without a Zone

Effect: Stored values cannot be compared or converted reliably.

Fix: Store UTC (or store the time zone identifier alongside local times when the local wall time itself matters, such as for future recurring events).

Using Fixed Offsets or Abbreviations

Effect: Wrong times during part of the year in DST regions; ambiguous abbreviations.

Fix: Use IANA identifiers such as Europe/London.

Comparing Formatted Times From Different Zones

Effect: "18:30" UTC appears earlier than "23:59" IST even when it is later.

Fix: Compare date objects or timestamps, not formatted strings.

Assuming a Day Always Has 24 Hours

Effect: Off-by-one-hour errors around DST changes.

Fix: Decide between calendar arithmetic (+1 day) and elapsed time (PT24H).


Best Practices

  • Set an explicit default time zone, commonly UTC on servers.
  • Store moments in UTC; convert to the user's time zone only for display.
  • Use IANA identifiers and validate user-supplied zones against listIdentifiers().
  • Create date objects with explicit DateTimeZone arguments.
  • Choose calendar or elapsed-time arithmetic deliberately in DST regions.

Official reference: https://www.php.net/manual/en/timezones.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about Timezones and get answers drawn from it.

Signed-in readers only.