Codectionary / Developer documentation / PHP

Parse Known Date Formats Safely

Use createFromFormat, parser diagnostics and a round-trip check to reject invalid calendar dates.

What it is and why to use it

A form field documented as YYYY-MM-DD needs a predictable parser rather than a broad natural-language date guess. DateTimeImmutable::createFromFormat() parses according to specified format characters. Parsing alone is not strict validation: impossible dates can be normalised with warnings. A reliable check must inspect diagnostics and confirm that formatting the result reproduces the intended input.

How it works

The ! in !Y-m-d resets unspecified fields, so the missing time starts at midnight instead of the current time. Read getLastErrors immediately after parsing. It returns diagnostic counts, or false when there are no warnings or errors on PHP 8.2 and later. Treat a false result from createFromFormat, any parser warning/error, or a failed round-trip as invalid.

Common mistakes and limitations

Do not accept a non-false date object as proof that the date existed. February 30 can overflow into March. A request field must first be a string of the allowed shape and length; embedded NUL bytes can cause ValueError. This guide uses exact fixed inputs and an explicit UTC zone, not unrestricted HTTP request data.

Run the examples locally

Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.

The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.

These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.

Check your interpreter, lint and run one saved example

php -v
php -l example.php
php example.php

Continue learning

Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.

Syntax

$date = DateTimeImmutable::createFromFormat('!Y-m-d', $text, new DateTimeZone('UTC'));

Examples

Parse an exact date with a predictable time

Accept a valid leap-year date and reset unspecified time fields.

<?php
declare(strict_types=1);

$text = '2024-02-29';
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $text, new DateTimeZone('UTC'));
$errors = DateTimeImmutable::getLastErrors();
$clean = $errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0);
if ($date !== false && $clean && $date->format('Y-m-d') === $text) {
    echo $date->format('Y-m-d H:i:s'), PHP_EOL;
} else {
    echo 'Invalid date', PHP_EOL;
}
  1. The format’s ! resets the unspecified clock fields and Y-m-d describes year, month and day.
  2. The diagnostics check supports both older array results and PHP 8.2+ returning false when parsing is clean.
  3. The final format comparison ensures the date round-trips exactly. February 29 is valid in 2024, so midnight is printed.
  4. Expected output: 2024-02-29 00:00:00

Reject a date that normalises with a warning

Detect an impossible date even when the parser can produce an object.

<?php
declare(strict_types=1);

$text = '2025-02-30';
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $text, new DateTimeZone('UTC'));
$errors = DateTimeImmutable::getLastErrors();
$clean = $errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0);
$valid = $date !== false && $clean && $date->format('Y-m-d') === $text;
echo $valid ? 'Accepted' : 'Invalid date', PHP_EOL;
  1. February does not contain day 30, so parsing produces a warning even if an adjusted date object is returned.
  2. The clean flag becomes false and prevents acceptance.
  3. The exact-format round-trip is a second check against normalisation. This approach is useful for controlled booking and calendar date fields.
  4. Expected output: Invalid date

Best practices

  • Inspect warnings and errors immediately after parsing.
  • Round-trip exact formats and validate the input’s type and shape.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading