{
    "slug": "php_date_immutable",
    "term": "DateTimeImmutable vs DateTime",
    "category": "php",
    "difficulty": "beginner",
    "short": "DateTimeImmutable returns a new object for every modification — the original is never changed. DateTime modifies in place. Prefer DateTimeImmutable in all new code to avoid subtle bugs where shared date objects are accidentally mutated.",
    "long": "DateTime and DateTimeImmutable both implement DateTimeInterface and accept the same constructor arguments and format strings. The difference is mutation: DateTime::modify(), add(), sub(), and setDate() mutate the object and return $this. DateTimeImmutable::modify() returns a new object with the change applied — the original is unchanged. This matters when a date is passed to a function that calls modify() — with DateTime, the caller's date changes too; with DateTimeImmutable, it cannot. The DateTimeInterface type hint accepts both, so you can write functions that work with either while defaulting to the immutable variant.",
    "aliases": [
        "DateTimeImmutable",
        "DateTime immutable",
        "PHP date immutable",
        "DateTimeInterface"
    ],
    "tags": [
        "php-stdlib",
        "datetime",
        "immutability",
        "bugs"
    ],
    "misconception": "DateTimeImmutable is slower because it creates new objects. The object creation overhead is negligible — a few microseconds per operation. The correctness benefit far outweighs the cost.",
    "why_it_matters": "Accidentally mutating a shared DateTime object is a classic PHP bug — a function that 'just reads' a date may call modify() internally, silently changing the caller's date. This is especially dangerous with dates passed through multiple layers of business logic. DateTimeImmutable makes it structurally impossible.",
    "common_mistakes": [
        "Calling modify() on a DateTimeImmutable and ignoring the return value — the call does nothing visible because the original is unchanged and the new object is discarded.",
        "Type-hinting DateTime instead of DateTimeInterface — this rejects DateTimeImmutable instances; use DateTimeInterface to accept both.",
        "Using date_create() helper functions which return DateTime not DateTimeImmutable — use 'new DateTimeImmutable()' or DateTimeImmutable::createFromFormat().",
        "Storing mutable DateTime objects in value objects or entities — any code that holds the same reference can accidentally change the date."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "php_date_timezone",
        "immutability",
        "value_object",
        "legacy_date_functions"
    ],
    "prerequisites": [],
    "refs": [
        "https://www.php.net/DateTimeImmutable",
        "https://www.php.net/DateTimeInterface"
    ],
    "bad_code": "<?php\n// ❌ DateTime mutation bug — modify() changes the original\nfunction addBusinessDays(DateTime $date, int $days): DateTime\n{\n    for ($i = 0; $i < $days; $i++) {\n        $date->modify('+1 day'); // Mutates the caller's DateTime!\n        if ((int) $date->format('N') >= 6) {\n            $date->modify('+2 days');\n        }\n    }\n    return $date;\n}\n\n$orderDate = new DateTime('2026-01-10');\n$dueDate = addBusinessDays($orderDate, 3);\n// $orderDate is now '2026-01-15' — silently mutated!",
    "good_code": "<?php\n// ✅ DateTimeImmutable — originals are never modified\nfunction addBusinessDays(DateTimeImmutable $date, int $days): DateTimeImmutable\n{\n    $current = $date;\n    for ($i = 0; $i < $days; $i++) {\n        $current = $current->modify('+1 day'); // Returns new object\n        if ((int) $current->format('N') >= 6) {\n            $current = $current->modify('+2 days');\n        }\n    }\n    return $current;\n}\n\n$orderDate = new DateTimeImmutable('2026-01-10');\n$dueDate = addBusinessDays($orderDate, 3);\n// $orderDate is still '2026-01-10' — unchanged",
    "quick_fix": "Replace 'new DateTime()' with 'new DateTimeImmutable()' everywhere. Where you used '$date->modify('+1 day')' and expected mutation, capture the return value: '$nextDay = $date->modify('+1 day');'.",
    "effort": "low",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/php_date_immutable",
        "html_url": "https://codeclaritylab.com/glossary/php_date_immutable",
        "json_url": "https://codeclaritylab.com/glossary/php_date_immutable.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[DateTimeImmutable vs DateTime](https://codeclaritylab.com/glossary/php_date_immutable) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/php_date_immutable"
            }
        }
    }
}