PHP Advent

#[Language]

PHP Date Format: date() and DateTimeImmutable Guide

By Rodney Renner ·

An illuminated watchmaker desk features an open pocket watch mechanism with exposed brass gears, precision tweezers, and an open notebook beside a laptop displaying abstract code.

To format a date in PHP, use the procedural date() function for Unix timestamps or the format() method on DateTimeImmutable for object-oriented code. Both use the same format characters: Y-m-d outputs a standard year-month-day date such as 2026-11-22, while H:i:s formats a 24-hour time with minutes and seconds. DateTimeImmutable keeps timezone rules with the date and prevents code elsewhere in the application from accidentally changing the same object.

Dates appear in database records, API payloads, audit logs, and user interfaces. Each needs the right format and timezone. A wrong format character can put a month where the minutes belong; an unescaped letter or a week-year token can produce an equally confusing result. Standards such as ISO 8601 and RFC 3339 give you consistent formats for exchanging timestamps.

Understanding Date Formatting in PHP

PHP has procedural functions that work with integer Unix timestamps and an object-oriented API built around DateTimeInterface.

Both use the same format characters. When you pass a string like 'Y-m-d H:i:s' to a formatting function, PHP parses each character as a formatting directive. If a character matches a recognized token, PHP replaces it with the corresponding date component. Characters that do not match tokens, such as hyphens, colons, spaces, and slashes, pass through unchanged.

The PHP date formatting manual lists all the tokens. Use them to turn timestamps into readable dates for a display or standardized strings for another system. For localized interfaces, you also need the language-specific formatting covered below.

Procedural Date Formatting: The date() Function

The procedural date() function has been part of PHP since early releases. It accepts a format string and an optional integer Unix timestamp:

<?php

$formatted = date('Y-m-d', time());
echo $formatted;

If you omit the timestamp parameter or pass null, date() defaults to the current system time returned by time().

You can format the current time, a stored timestamp, or a filename:

<?php

date_default_timezone_set('UTC');

// Format current Unix timestamp using the runtime default timezone
$currentDate = date('Y-m-d H:i:s');
echo $currentDate; // Example output: 2026-11-22 18:30:00

// Format a specific Unix timestamp
$timestamp = 1774180800;
$formatted = date('l, F j, Y', $timestamp);
echo $formatted; // Output: Sunday, March 22, 2026

// Generate a compact timestamp for file naming
$filename = 'backup-' . date('Ymd-His') . '.tar.gz';
echo $filename; // Example output: backup-20261122-183000.tar.gz

date() is concise enough for simple scripts. In a larger application, watch for these limitations:

  1. It relies on the global default timezone configured in php.ini or set at runtime by date_default_timezone_set(). If another component or library changes the runtime timezone, all subsequent date() calls produce shifted values.
  2. Unix timestamps represent integer seconds since January 1, 1970 UTC. They do not store timezone context or sub-second microsecond precision.
  3. Procedural date math relies on adding seconds or calling strtotime(). Adding raw seconds across a daylight saving time transition can leave a calculation off by one hour.

The PHP manual for date() describes how the function behaves. Production PHP code increasingly uses date objects to avoid these problems.

Format Dates with DateTimeImmutable

PHP 5.2 introduced the DateTime class, and PHP 5.5 added DateTimeImmutable. Use DateTimeImmutable to represent calendar dates and timestamps in new PHP code.

Why Immutability Matters

The original DateTime class is mutable: modify(), add(), and sub() change the existing object. That matters when you pass a date to a helper function or share it between services. A helper that changes a date stored in a domain entity changes what every other caller sees too.

DateTimeImmutable avoids that problem. Its transformation methods return a new instance, so the original date stays unchanged:

<?php

// Problem with mutable DateTime: unexpected side effects
function printEventWindow(DateTime $start): void
{
    $end = $start->modify('+7 days');
    echo 'Window: ' . $start->format('Y-m-d') . ' to ' . $end->format('Y-m-d') . PHP_EOL;
}

$meeting = new DateTime('2026-06-01');
printEventWindow($meeting);
// Both $start and $end print 2026-06-08 because modify() mutated $start in place!

// Safe approach with DateTimeImmutable
function printEventWindowSafe(DateTimeImmutable $start): void
{
    $end = $start->modify('+7 days');
    echo 'Window: ' . $start->format('Y-m-d') . ' to ' . $end->format('Y-m-d') . PHP_EOL;
}

$safeMeeting = new DateTimeImmutable('2026-06-01');
printEventWindowSafe($safeMeeting);
// Correctly outputs: Window: 2026-06-01 to 2026-06-08

The PHP manual for DateTimeImmutable documents the full interface. You can also use DateTimeImmutable with readonly properties to protect an object's state. Our guide to PHP property hooks covers related features, including typed properties and asymmetric visibility.

Formatting with DateTimeImmutable

Call format() to format the timestamp in the object's own timezone. The format characters are the same ones you use with date():

<?php

$timezone = new DateTimeZone('America/Chicago');
$orderDate = new DateTimeImmutable('2026-11-22 14:15:30', $timezone);

// Format with standard date and time tokens
echo $orderDate->format('Y-m-d H:i:s');
// Output: 2026-11-22 14:15:30

// Include timezone name and offset
echo $orderDate->format('Y-m-d H:i:s e (P)');
// Output: 2026-11-22 14:15:30 America/Chicago (-06:00)

The Essential PHP Date Format Characters

PHP has more than thirty format characters. Case matters: a lowercase and uppercase letter can produce quite different output.

Year Format Characters

  • Y: A full four-digit numeric representation of a year. Examples: 2024, 2025, 2026. This is the standard token for calendar dates.
  • y: A two-digit representation of a year with leading zero where applicable. Examples: 24, 25, 26.
  • o: The ISO-8601 week-numbering year. This has the same value as Y, except when the ISO week number W belongs to the previous or next calendar year. For example, December 31 may belong to week 1 of the following year. Using o ensures year and week alignment.
  • L: Whether it is a leap year. Returns 1 if it is a leap year, and 0 otherwise.
<?php

$date = new DateTimeImmutable('2026-01-01');
echo $date->format('Y'); // Output: 2026
echo $date->format('y'); // Output: 26
echo $date->format('L'); // Output: 0 (2026 is not a leap year)

Month Format Characters

  • m: Numeric representation of a month with leading zeros (01 through 12).
  • n: Numeric representation of a month without leading zeros (1 through 12).
  • M: A short textual representation of a month, three letters (Jan through Dec).
  • F: A full textual representation of a month (January through December).
  • t: The number of days in the given month (28 through 31).
<?php

$date = new DateTimeImmutable('2026-03-05');
echo $date->format('m'); // Output: 03
echo $date->format('n'); // Output: 3
echo $date->format('M'); // Output: Mar
echo $date->format('F'); // Output: March
echo $date->format('t'); // Output: 31 (March has 31 days)

Day Format Characters

  • d: Day of the month, two digits with leading zeros (01 through 31).
  • j: Day of the month without leading zeros (1 through 31).
  • D: A textual representation of a day, three letters (Mon through Sun).
  • l (lowercase L): A full textual representation of the day of the week (Sunday through Saturday).
  • N: The ISO-8601 numeric representation of the day of the week (1 for Monday through 7 for Sunday).
  • w: Numeric representation of the day of the week (0 for Sunday through 6 for Saturday).
  • S: English ordinal suffix for the day of the month, two characters (st, nd, rd, or th). Commonly paired with j.
  • z: The day of the year, starting from zero (0 through 365).
<?php

$date = new DateTimeImmutable('2026-11-03');
echo $date->format('d');    // Output: 03
echo $date->format('j');    // Output: 3
echo $date->format('jS');   // Output: 3rd
echo $date->format('D');    // Output: Tue
echo $date->format('l');    // Output: Tuesday
echo $date->format('N');    // Output: 2 (Tuesday is day 2 in ISO-8601)
echo $date->format('w');    // Output: 2 (Tuesday is day 2 where Sunday is 0)
echo $date->format('z');    // Output: 306

Time Format Characters: Hours, Minutes, and Seconds

  • H: 24-hour format of an hour with leading zeros (00 through 23).
  • G: 24-hour format of an hour without leading zeros (0 through 23).
  • h: 12-hour format of an hour with leading zeros (01 through 12).
  • g: 12-hour format of an hour without leading zeros (1 through 12).
  • i: Minutes with leading zeros (00 through 59). Note that i represents minutes because m is reserved for months.
  • s: Seconds with leading zeros (00 through 59).
  • A: Uppercase Ante meridiem and Post meridiem (AM or PM).
  • a: Lowercase Ante meridiem and Post meridiem (am or pm).
<?php

$morning = new DateTimeImmutable('2026-11-22 09:05:08');
echo $morning->format('H:i:s');    // Output: 09:05:08
echo $morning->format('g:i:s A');  // Output: 9:05:08 AM

$evening = new DateTimeImmutable('2026-11-22 21:45:30');
echo $evening->format('H:i:s');    // Output: 21:45:30
echo $evening->format('h:i:s A');  // Output: 09:45:30 PM
echo $evening->format('g:i a');    // Output: 9:45 pm

Fractional Seconds: Milliseconds and Microseconds

  • v: Milliseconds as three digits. Supported in PHP 7.0 and later.
  • u: Microseconds as six digits.

Fractional seconds help distinguish events that happen within the same second, which is useful in busy event logs and distributed traces:

<?php

$now = new DateTimeImmutable();
echo $now->format('H:i:s.v'); // Example: 18:30:00.412
echo $now->format('H:i:s.u'); // Example: 18:30:00.412891

date('u') returns 000000 when formatting the current time because time() provides only integer seconds. Create DateTimeImmutable without arguments to capture microseconds from the operating system clock.

Timezone Format Characters

  • e: The timezone identifier. Examples: UTC, America/New_York, Europe/Berlin.
  • P: Difference to Greenwich time (GMT) with colon between hours and minutes. Examples: +02:00, -05:00, +00:00.
  • O: Difference to Greenwich time without colon. Examples: +0200, -0500.
  • T: Timezone abbreviation. Examples: EST, MDT, UTC, CEST.
  • Z: Timezone offset in seconds. Negative for west of UTC, positive for east (-43200 through 50400).
<?php

$tz = new DateTimeZone('Europe/Amsterdam');
$date = new DateTimeImmutable('2026-07-15 12:00:00', $tz);

echo $date->format('e'); // Output: Europe/Amsterdam
echo $date->format('P'); // Output: +02:00 (during Central European Summer Time)
echo $date->format('O'); // Output: +0200
echo $date->format('T'); // Output: CEST
echo $date->format('Z'); // Output: 7200

Full Date and Time Shortcuts

These tokens produce a complete date string or a Unix timestamp:

  • c: Full ISO 8601 date string, equivalent to Y-m-d\TH:i:sP. Example: 2026-11-22T18:30:00+00:00.
  • r: RFC 2822 formatted date, commonly used in email headers. Example: Sun, 22 Nov 2026 18:30:00 +0000.
  • U: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), identical to time().
<?php

$date = new DateTimeImmutable('2026-11-22 18:30:00', new DateTimeZone('UTC'));

echo $date->format('c'); // Output: 2026-11-22T18:30:00+00:00
echo $date->format('r'); // Output: Sun, 22 Nov 2026 18:30:00 +0000
echo $date->format('U'); // Output: 1795372200

ISO 8601, RFC 3339, and Predefined Format Constants

Use a consistent timestamp format in web APIs and stored data so other systems can parse it without ambiguity.

ISO 8601 and its profile RFC 3339 are widely used internet standards. They are similar, but their rules for timezone offsets differ.

PHP defines format constants on DateTimeInterface, documented in the PHP DateTime constants manual:

  • DateTimeInterface::ATOM: Format Y-m-d\TH:i:sP, matching RFC 3339 and standard ISO 8601.
  • DateTimeInterface::RFC3339: Format Y-m-d\TH:i:sP.
  • DateTimeInterface::RFC3339_EXTENDED: Format Y-m-d\TH:i:s.vP, including millisecond precision.
  • DateTimeInterface::ISO8601_EXPANDED: Introduced in PHP 8.2, format X-m-d\TH:i:sP, accommodating years with expanded notations.
  • DateTimeInterface::W3C: Format Y-m-d\TH:i:sP, compliant with World Wide Web Consortium recommendations.
<?php

$date = new DateTimeImmutable('2026-11-22 16:20:00.450', new DateTimeZone('UTC'));

// Standard RFC 3339 representation
echo $date->format(DateTimeInterface::RFC3339);
// Output: 2026-11-22T16:20:00+00:00

// Extended RFC 3339 with milliseconds
echo $date->format(DateTimeInterface::RFC3339_EXTENDED);
// Output: 2026-11-22T16:20:00.450+00:00

Watch for a historical quirk: the constant DateTimeInterface::ISO8601 uses the format Y-m-d\TH:i:sO. Because it uses O instead of P, it omits the colon between the hours and minutes of the timezone offset (producing +0000 rather than +00:00). This violates strict ISO 8601 requirements. For modern web services, use DateTimeInterface::ATOM or DateTimeInterface::RFC3339 instead of DateTimeInterface::ISO8601.

Working with Timezones and Daylight Saving Time

An event's timestamp and its local display time are different things. Mixing them up causes timezone bugs.

A timestamp identifies a single point in time. A timezone supplies an offset and the historical and future daylight saving time rules for a geographic location.

DateTimeZone holds these rules. The PHP manual for DateTimeZone documents the DateTimeZone class and its timezone identifier and offset methods.

Three synchronized brass horological dials on a dark timber workbench connected by glowing fiber-optic light conduits represent UTC normalization and local timezone conversion.

The Recommended Architecture: Store UTC, Display Local

For application timestamps, use this approach:

  1. Convert incoming timestamps to UTC immediately.
  2. Store all database date and time columns in UTC or as raw Unix timestamps.
  3. Convert to the user's or merchant's local timezone when formatting output.
<?php

// 1. Ingestion: an event occurs in Tokyo
$tokyoTz = new DateTimeZone('Asia/Tokyo');
$eventTime = new DateTimeImmutable('2026-11-23 09:00:00', $tokyoTz);

// 2. Normalization: convert to UTC for database persistence
$utcTz = new DateTimeZone('UTC');
$storageTime = $eventTime->setTimezone($utcTz);

echo 'Persisted to DB: ' . $storageTime->format(DateTimeInterface::RFC3339) . PHP_EOL;
// Persisted to DB: 2026-11-23T00:00:00+00:00

// 3. Presentation: display to an administrator in London
$londonTz = new DateTimeZone('Europe/London');
$displayTime = $storageTime->setTimezone($londonTz);

echo 'Admin Display: ' . $displayTime->format('F j, Y, g:i A T') . PHP_EOL;
// Admin Display: November 23, 2026, 12:00 AM GMT

Timezone Hazards in Long-Running Worker Processes

In traditional PHP-FPM setups, calling date_default_timezone_set('America/Los_Angeles') changes the timezone for the active HTTP request, and the process state is cleared at request shutdown.

In long-running worker environments such as FrankenPHP and RoadRunner, worker processes serve multiple requests. Calling date_default_timezone_set() inside a request alters the global timezone for subsequent requests handled by that worker. That can leak timezone settings between tenants: one user's request changes how the worker formats dates for other users.

Avoid date_default_timezone_set() inside request handlers. Set the application default to UTC in your bootstrap configuration, and pass explicit DateTimeZone instances to DateTimeImmutable objects whenever formatting dates.

Early community articles such as Derick Rethans' analysis of time calculations in what time is it and Evert Pot's overview of dates and times describe similar problems with implicit timezone state.

Escaping Literal Text in Format Strings

Words in a format string can contain letters that PHP treats as date tokens:

<?php

$date = new DateTimeImmutable('2026-11-22 14:00:00');

// Unintended formatting: characters match formatting tokens
echo $date->format('Today is l'); // The letters in "Today is" are interpreted as format tokens

In the word "Today", PHP interprets T as a timezone abbreviation, o as a week-numbering year, d as day of the month, a as am/pm, and y as a two-digit year. The i and s in "is" are tokens too. The result is not the literal phrase.

To include literal characters in a format string, escape each character with a backslash.

Single Quotes Versus Double Quotes

In PHP, escape handling differs between single and double quotes:

  • In single-quoted strings ('...'), PHP treats \ as a literal backslash unless followed by another backslash or a single quote. Writing '\T\o\d\a\y' passes the backslashes directly to format().
  • In double-quoted strings ("..."), PHP evaluates escape sequences like \n (newline), \t (tab), and \r (carriage return). If your format string contains \t, PHP substitutes an ASCII tab character before the date formatter ever sees it.

Use single-quoted strings when escaping format directives to avoid this confusion:

<?php

$date = new DateTimeImmutable('2026-11-22 14:05:00');

// Escaping literal text in single quotes
echo $date->format('\T\o\d\a\y \i\s l, F jS, Y');
// Output: Today is Sunday, November 22nd, 2026

// Escaping individual words
echo $date->format('l \a\t g:i A');
// Output: Sunday at 2:05 PM

// Building complex human-readable strings
echo $date->format('\R\e\p\o\r\t \g\e\n\e\r\a\t\e\d \o\n Y-m-d \a\t H:i:s');
// Output: Report generated on 2026-11-22 at 14:05:00

Parse and Validate Date Strings

Dates from users and APIs arrive as strings. Before you format them for output, parse and validate the input.

DateTimeImmutable::createFromFormat() parses a custom date string using the same format tokens:

<?php

$input = '22/11/2026 15:30:00';
$format = 'd/m/Y H:i:s';
$timezone = new DateTimeZone('UTC');

$date = DateTimeImmutable::createFromFormat($format, $input, $timezone);

if ($date === false) {
    throw new InvalidArgumentException('Date does not match format ' . $format);
}

// Check for warnings or loose parsing
$errors = DateTimeImmutable::getLastErrors();
if ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) {
    throw new InvalidArgumentException('Malformed date input');
}

echo $date->format('Y-m-d H:i:s');
// Output: 2026-11-22 15:30:00

Always inspect DateTimeImmutable::getLastErrors(). An overflowing date such as February 31 can produce an object with a warning. Trailing characters normally produce an error; the + parsing specifier changes that to a warning. Checking for a valid object and zero errors and warnings rejects both cases. Since PHP 8.2, getLastErrors() returns false when there are no warnings or errors.

Before and After: Refactoring Date Logic in an Application Entity

To see how these principles improve real software, examine an invoice service that formats dates for billing records and customer notifications.

Before: Procedural State and Fragile String Concatenation

In this legacy implementation, date formatting relies on procedural time(), string concatenations, mutable DateTime instances, and global timezone modification:

<?php

class LegacyInvoiceFormatter
{
    public function formatInvoiceSummary(int $createdTimestamp, string $customerTz): array
    {
        // Global timezone mutation: pollutes runtime state
        date_default_timezone_set($customerTz);

        // Bug: 'm' is used for both month and minutes
        $formattedDate = date('Y-m-d H:m:s', $createdTimestamp);

        // Mutable DateTime object calculation
        $dueDate = new DateTime();
        $dueDate->setTimestamp($createdTimestamp);
        
        // Intended due date is 30 days later, with a 14-day grace period
        $dueDate->modify('+30 days');
        $gracePeriod = $dueDate->modify('+14 days');

        return [
            'created' => $formattedDate,
            'due' => $dueDate->format('Y-m-d'),
            'grace_period' => $gracePeriod->format('Y-m-d'),
        ];
    }
}

This code has three distinct bugs:

  1. date_default_timezone_set() pollutes the global process state, creating concurrency defects.
  2. date('Y-m-d H:m:s') outputs the month number in place of minutes, rendering 14:11:00 instead of 14:35:00 for a November date.
  3. The second modify() call mutates $dueDate again, causing both 'due' and 'grace_period' to reflect the end of the grace period.

After: Type-Safe, Immutable Date Formatting

The refactored implementation uses DateTimeImmutable, explicit timezone instances, standard RFC 3339 formats for persistence, and correct format characters. The readonly class declaration requires PHP 8.2 or newer:

<?php

final readonly class InvoiceSummary
{
    public function __construct(
        public DateTimeImmutable $createdAt,
        public DateTimeImmutable $dueAt,
        public DateTimeImmutable $gracePeriodEndsAt,
    ) {}

    public static function create(
        DateTimeImmutable $createdAt,
        int $dueDays = 30,
        int $gracePeriodDays = 14,
    ): self {
        $dueAt = $createdAt->modify('+' . $dueDays . ' days');
        $gracePeriodEndsAt = $dueAt->modify('+' . $gracePeriodDays . ' days');

        return new self($createdAt, $dueAt, $gracePeriodEndsAt);
    }

    public function formatForCustomer(DateTimeZone $customerTimezone): array
    {
        return [
            'created' => $this->createdAt->setTimezone($customerTimezone)->format('F j, Y, g:i A T'),
            'due' => $this->dueAt->setTimezone($customerTimezone)->format('F j, Y'),
            'grace_period' => $this->gracePeriodEndsAt->setTimezone($customerTimezone)->format('F j, Y'),
        ];
    }

    public function formatForApi(): array
    {
        $utc = new DateTimeZone('UTC');
        return [
            'created_at' => $this->createdAt->setTimezone($utc)->format(DateTimeInterface::RFC3339),
            'due_at' => $this->dueAt->setTimezone($utc)->format(DateTimeInterface::RFC3339),
            'grace_period_ends_at' => $this->gracePeriodEndsAt->setTimezone($utc)->format(DateTimeInterface::RFC3339),
        ];
    }
}

The refactored design eliminates global state, separates persistence formatting from display formatting, and keeps the dates immutable. Static analysis with tools such as PHPStan can flag calls that pass the wrong type to these methods.

A split workbench view contrasts a tangled jumble of loose wires and disassembled clock parts on the left with an enclosed, precision-machined brass chronometer on the right.

Common PHP Date Formatting Mistakes and Pitfalls

1. Using Lowercase y Instead of Uppercase Y

The token y outputs a two-digit year (26), whereas Y outputs a four-digit year (2026). In database queries and API payloads, writing 'y-m-d' generates dates like '26-11-22', leaving the receiving system to interpret the abbreviated year.

2. Confusing the Calendar Year Y with the ISO Week Year o

The token o returns the ISO-8601 week-numbering year, which pairs with the week number W. If December 31 falls on a Monday or Tuesday that belongs to week 1 of the upcoming year, date('Y-m-d', $ts) and date('o-W', $ts) diverge.

If you write date('o-m-d'), a date on December 31, 2024 can output 2025-12-31. Never mix o with month m and day d. Use Y with m and d, and reserve o for pairing with W and N.

3. Using m Instead of i for Minutes

It is easy to write 'Y-m-d H:m:s'. Both "month" and "minute" start with m, but this pattern outputs the numeric month twice: once in the date and once in the time. The format token for minutes is i (representing "mInute"). The correct pattern is 'Y-m-d H:i:s'.

Watchmaker tweezers lift an isolated miniature brass gear above an intricate mechanical clockwork train on an illuminated wooden workbench.

4. Confusing 12-Hour and 24-Hour Specifiers

The token h represents 12-hour format with leading zeros (01 to 12), while H represents 24-hour format (00 to 23). If you use h without adding A or a to denote AM or PM, 02:00 could mean either 2:00 AM or 2:00 PM. For database storage and logging, always use 24-hour H. For user-facing 12-hour displays, always include A or a.

5. Mutating DateTime Objects in Loops

When aggregating records or building monthly calendar grids, using mutable DateTime objects inside a loop alters the base date on each iteration. Always use DateTimeImmutable when calculating date intervals across collections.

Frequently Asked Questions About PHP Date Formatting

How can I format dates in a language other than English?

date() and DateTimeImmutable::format() produce English month and day names (January, Mon, etc.). They do not translate those names for a locale.

To format dates in other languages such as Spanish, French, or German, use the IntlDateFormatter class provided by PHP's intl extension (backed by the ICU library):

<?php

$date = new DateTimeImmutable('2026-11-22 14:30:00', new DateTimeZone('Europe/Paris'));

// Format in French
$frenchFormatter = new IntlDateFormatter(
    'fr_FR',
    IntlDateFormatter::FULL,
    IntlDateFormatter::NONE,
    'Europe/Paris',
    IntlDateFormatter::GREGORIAN
);

echo $frenchFormatter->format($date);
// Output: dimanche 22 novembre 2026

// Format in German
$germanFormatter = new IntlDateFormatter(
    'de_DE',
    IntlDateFormatter::LONG,
    IntlDateFormatter::SHORT,
    'Europe/Berlin',
    IntlDateFormatter::GREGORIAN
);

echo $germanFormatter->format($date);
// Output: 22. November 2026 um 14:30

Why does date() show the wrong time on my server?

If date('H:i:s') outputs an unexpected hour, the PHP runtime timezone does not match your expectations. PHP relies on the date.timezone setting in php.ini. If that setting is missing, PHP defaults to UTC.

To inspect the active runtime timezone, run:

<?php

echo date_default_timezone_get();

What is the recommended date format for REST APIs and JSON responses?

For REST APIs and JSON payloads, use the standard RFC 3339 / ISO 8601 format with complete timezone information. Generate it with DateTimeInterface::RFC3339:

<?php

$date = new DateTimeImmutable('2026-11-22 18:30:00', new DateTimeZone('UTC'));
$jsonDate = $date->format(DateTimeInterface::RFC3339);
echo $jsonDate; // Output: 2026-11-22T18:30:00+00:00

When sorting timestamps or working with event logs that need millisecond precision, include fractional seconds using DateTimeInterface::RFC3339_EXTENDED:

<?php

$date = new DateTimeImmutable('2026-11-22 18:30:00.123', new DateTimeZone('UTC'));
$jsonDateWithMs = $date->format(DateTimeInterface::RFC3339_EXTENDED);
echo $jsonDateWithMs; // Output: 2026-11-22T18:30:00.123+00:00