PHP error guide

DateTime failed to parse time string: meaning and fix

Error summary

Parse external dates with a declared format, inspect DateTimeImmutable::getLastErrors, and reject warnings as well as errors.

What it means

Parse external dates with a declared format, inspect DateTimeImmutable::getLastErrors, and reject warnings as well as errors.

What the error means

The date parser cannot interpret the input as a valid supported date/time expression or detects invalid components.

Why PHP produces it

Free-form or malformed user data is passed to the DateTime constructor without an exact input contract.

PHP version notes

The behavior described for DateTime failed to parse time string applies to PHP 7.4–8.4 unless a narrower version is stated; exact wording can vary by SAPI and patch release.

Most common causes

  • Month, day, or time components are out of range.
  • Ambiguous locale formatting is interpreted unexpectedly.
  • Trailing bytes or unexpected timezone text remain in the value.

Minimal examples

BAD — reproduces the problem

php
$date = new DateTimeImmutable($_POST["date"]);

FIXED — safer pattern

php
$date = DateTimeImmutable::createFromFormat("!Y-m-d", $input); if ($date === false) { throw new InvalidArgumentException(); }

Step-by-step diagnosis

  1. Record the input format class without logging sensitive surrounding data.
  2. Use createFromFormat with ! and inspect getLastErrors.
  3. Check both warning_count and error_count because invalid dates may normalize with warnings.

Fixes

Parse and validate an exact format

Reject any parser warning or error instead of accepting normalized dates.

php
$date = DateTimeImmutable::createFromFormat("!Y-m-d", $input);
$errors = DateTimeImmutable::getLastErrors();
if ($date === false || ($errors !== false && ($errors["warning_count"] || $errors["error_count"]))) {
    throw new InvalidArgumentException("Invalid date");
}

Common mistakes when fixing it

  • Using strtotime and treating false as timestamp zero.
  • Ignoring parser warnings for impossible calendar dates.
  • Depending on locale-specific ambiguous forms.

How to prevent it

  • Accept ISO or another documented exact format.
  • Validate parser warnings and errors.
  • Store normalized timezone-aware values.

Web server / environment notes

cli, fpm, apache. Date parsing behavior is independent of SAPI but affected by explicit/default timezone.

Tags: cli,fpm,apache

Categories