Library contents

PHP DateTimeImmutable::createFromFormat

DateTimeImmutable::createFromFormat can normalize an impossible date and return an object. Inspect getLastErrors immediately to detect parsing warnings.

A simple example

DateTimeImmutable::createFromFormat

  1. Start with Text 2024-01-02
  2. Do this Parse year, month and day
  3. Result January 2, 2024
The input pieces match the indicated format and form a valid date.

Syntax

PHP syntax
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $text)
Run this example in PHP

Save the program as lesson.php. Use PHP 8.2 or later.

php lesson.php

Reject a date that the parser normalizes

A reporting or booking deadline falls close to the end of a month. Use a calendar operation and validate the input so a leap day or an invalid date cannot silently shift the deadline.

From the programdeclare(strict_types=1)
First output line2024-03-01
lesson.php
<?php
declare(strict_types=1);

foreach (['2024-02-29', '2023-02-29'] as $text) {
    $date = DateTimeImmutable::createFromFormat('!Y-m-d', $text, new DateTimeZone('UTC'));
    $errors = DateTimeImmutable::getLastErrors();
    if ($date === false || $errors !== false || $date->format('Y-m-d') !== $text) {
        echo "invalid date\n";
        continue;
    }
    echo $date->modify('+1 day')->format('Y-m-d') . "\n";
}
Output
2024-03-01
invalid date

The leading exclamation mark resets unspecified fields. A format round trip also enforces the exact input shape. In PHP 8.2 and later getLastErrors returns false when parsing was clean.

PHP documentation for DateTimeImmutable::createFromFormat

Advertisements

Return a borrowed microscope

A school lends a microscope two days before the end of February in a leap year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?

Given28 February 2024 + 2 days
Worked result2024-03-01

Send a year-end reminder

A gallery schedules its reminder one day after the final day of the year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?

Given31 December 2026 + 1 day
Worked result2027-01-01