PHP Code Examples

Parse and Format Dates with DateTimeImmutable

Use DateTimeImmutable and explicit time zones to parse, modify, and format dates predictably.

Example

<?php
$timezone = new DateTimeZone('Europe/Istanbul');

$date = new DateTimeImmutable('2026-11-21 09:30:00', $timezone);
$nextWeek = $date->modify('+7 days');

echo $date->format('Y-m-d H:i:s');
echo $nextWeek->format('d.m.Y');

Parse user input carefully

$input = '21.11.2026';
$date = DateTimeImmutable::createFromFormat(
    '!d.m.Y',
    $input,
    $timezone
);

$errors = DateTimeImmutable::getLastErrors();

if ($date === false ||
    ($errors !== false &&
     ($errors['warning_count'] > 0 || $errors['error_count'] > 0))) {
    throw new InvalidArgumentException('Invalid date.');
}

Notes

Store timestamps consistently, commonly in UTC, and convert to the user's time zone for display. Avoid relying on the server's implicit default time zone.

Share this page Help other developers discover this resource.