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
- Start with Text 2024-01-02
- Do this Parse year, month and day
- Result January 2, 2024
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.
<?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";
}
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
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?
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?