0Pricing
PHP Academy · Lesson

Timezones in PHP

Handle multiple timezones with DateTimeZone and date_default_timezone_set.

Timezones in PHP is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Timezones Matter

If your application serves users globally, timezone handling is critical. PHP uses timezone-aware functions and classes to handle conversions correctly.

  • Always store times in UTC in the database
  • Convert to user's local timezone only for display

date_default_timezone_set()

Set the default timezone for all date functions:

<?php
// Set at the top of your script or in php.ini
date_default_timezone_set('Europe/Istanbul');

echo date('Y-m-d H:i:s');  // local Istanbul time
echo PHP_EOL;

date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s');  // UTC time

// Or set in php.ini:
// date.timezone = "Europe/London"

DateTimeZone Class

Create timezone objects to use with DateTime:

<?php
$utc      = new DateTimeZone('UTC');
$istanbul = new DateTimeZone('Europe/Istanbul');
$ny       = new DateTimeZone('America/New_York');

$dt = new DateTime('now', $utc);
echo $dt->format('Y-m-d H:i:s T');  // UTC time

Converting Between Timezones

Convert a DateTime to a different timezone with setTimezone():

<?php
$utcTime = new DateTime('2024-05-27 12:00:00', new DateTimeZone('UTC'));

$istanbul = clone $utcTime;
$istanbul->setTimezone(new DateTimeZone('Europe/Istanbul'));

$newYork = clone $utcTime;
$newYork->setTimezone(new DateTimeZone('America/New_York'));

echo 'UTC:      ' . $utcTime->format('H:i T')  . PHP_EOL;
echo 'Istanbul: ' . $istanbul->format('H:i T') . PHP_EOL;
echo 'New York: ' . $newYork->format('H:i T')  . PHP_EOL;

getOffset() and DST

Get the UTC offset in seconds and check for DST:

<?php
$tz = new DateTimeZone('America/New_York');
$dt = new DateTime('now', $tz);

$offset = $tz->getOffset($dt);        // offset in seconds
$offsetHours = $offset / 3600;
echo 'Offset: ' . $offsetHours . 'h'; // e.g. -5 or -4 in DST

$transitions = $tz->getTransitions(
    strtotime('2024-01-01'),
    strtotime('2024-12-31')
);
echo 'DST changes in 2024: ' . count($transitions);

Storing in UTC, Displaying Locally

Best practice: store UTC in database, show local time to user:

<?php
// Store: always save as UTC
$createdAt = (new DateTimeImmutable('now', new DateTimeZone('UTC')))
    ->format('Y-m-d H:i:s');

// Display: convert to user's timezone
$userTz  = new DateTimeZone($user['timezone'] ?? 'UTC');
$display = (new DateTime($createdAt, new DateTimeZone('UTC')))
    ->setTimezone($userTz)
    ->format('d M Y, H:i T');

User Timezone Detection

Detect and store the user's timezone for display purposes:

// JavaScript: detect and send to PHP:
// const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
// fetch('/api/set-timezone', { method:'POST', body: tz });

<?php
// PHP: validate and store
$tz = $_POST['timezone'] ?? 'UTC';
$valid = in_array($tz, DateTimeZone::listIdentifiers());

if ($valid) {
    $_SESSION['timezone'] = $tz;
    setcookie('user_tz', $tz, time() + 365 * 86400);
}

DateTimeZone::listIdentifiers()

Get all valid timezone identifiers:

<?php
// All identifiers
$all = DateTimeZone::listIdentifiers();
echo count($all) . ' timezones available';

// Filter by region
$europe = DateTimeZone::listIdentifiers(DateTimeZone::EUROPE);
echo count($europe) . ' European timezones';

// Check if a timezone string is valid
function isValidTimezone(string $tz): bool {
    return in_array($tz, DateTimeZone::listIdentifiers());
}
var_dump(isValidTimezone('Europe/Istanbul')); // true

Formatting Timezone Offset

Format timezone offset for display and APIs:

<?php
$dt = new DateTime('now', new DateTimeZone('America/Los_Angeles'));

echo $dt->format('P');     // +05:30 or -07:00
echo $dt->format('O');     // +0530 (no colon)
echo $dt->format('T');     // PST or PDT
echo $dt->format('e');     // America/Los_Angeles
echo $dt->format('Z');     // offset in seconds

Unix Timestamps Are Timezone-Neutral

Unix timestamps represent a specific moment in time regardless of timezone — use them for comparisons and calculations:

<?php
// These represent the same moment:
$utc   = new DateTime('2024-05-27 12:00:00', new DateTimeZone('UTC'));
$ist   = new DateTime('2024-05-27 15:00:00', new DateTimeZone('Asia/Kolkata'));

echo $utc->getTimestamp();   // same timestamp
echo $ist->getTimestamp();   // same timestamp

var_dump($utc->getTimestamp() === $ist->getTimestamp()); // true

date_create with Timezone

Procedural timezone handling with date_create and date_timezone_set:

<?php
$dt = date_create('now', timezone_open('UTC'));
$tz = timezone_open('Europe/Istanbul');

date_timezone_set($dt, $tz);
echo date_format($dt, 'Y-m-d H:i:s T');

// Check transition info
$info = timezone_transitions_get($tz);
echo 'Current offset: ' . ($info[0]['offset'] / 3600) . 'h';

Quick Check

Where should dates/times be stored in the database for a globally distributed application?

Recap: PHP Timezones

Timezone essentials:

  • Set default timezone with date_default_timezone_set()
  • Use DateTimeZone objects with DateTime
  • setTimezone() to convert between zones
  • Always store UTC in the database
  • Validate user timezones with DateTimeZone::listIdentifiers()
  • Unix timestamps are timezone-neutral moments in time

Frequently asked questions

Is the “Timezones in PHP” lesson free?

Yes — the full text of “Timezones in PHP” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Timezones in PHP”?

Handle multiple timezones with DateTimeZone and date_default_timezone_set. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Timezones in PHP” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Unix Timestamps and date()
  2. The DateTime Class
  3. Date Arithmetic with DateInterval
  4. Timezones in PHP
← Back to PHP Academy