Coding/Learn/php/php date time and formatting
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnDate, Time & DateTimeImmutable Objects
10 / 20 0%
Lesson 10 of 20
8 mins read

Date, Time & DateTimeImmutable Objects

PreviousNext Lesson
In Plain English

Handling dates and timezones reliably is vital for web backends. Learn legacy timestamp formatting via date() and time(), and transition to modern object-oriented DateTimeImmutable, DateInterval, and timezone conversions.

The Mental Model

"A raw UNIX timestamp is just a ticking counter of seconds since 1970. A DateTimeImmutable object is a precision atomic clock that knows the exact local daylight savings time in Tokyo, London, or New York."

Deep Dive: How It Works

Legacy date(): date("Y-m-d H:i:s") formats the current server timestamp.

DateTimeImmutable: Modern immutable object that returns a fresh instance on modification, preventing mutation bugs.

Timezones: Set default with date_default_timezone_set("UTC") or pass new DateTimeZone("America/New_York").

Date Intervals: $date->add(new DateInterval("P7D")) adds 7 days cleanly.

Syntax Blueprint

<?php

$now = new DateTimeImmutable("now", new DateTimeZone("UTC"));
$nextWeek = $now->modify("+7 days");
echo $nextWeek->format("Y-m-d");

Create DateTimeImmutable instances, modify with human intervals (+7 days), and format with format().

PointCore Rules to Remember

Point star
Prefer Immutable: Always use DateTimeImmutable instead of mutable DateTime to avoid shared state mutations across helper calls.
Point star
Standard UTC Storage: Store timestamps in UTC in the database, and convert to user local timezone only at display time.
Point star
Format Tokens: Y (4-digit year), m (2-digit month), d (day), H (24h hour), i (minute), s (second).

Common Beginner Traps & How to Fix Them

Mistake:Using mutable DateTime and modifying it inside a helper function, inadvertently mutating the original caller date.

Why it happens: DateTime methods mutate the object in place.

How to fix: Switch to DateTimeImmutable.

Pro Tip: Use date_create_from_format("d/m/Y", $input) to reliably parse foreign date strings without ambiguity.

Live Interactive Example

Hit Run Code to see it live
DateTimeImmutable Formatting and Interval Math
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
Output Console
Click "Run Code" to view the rendered output.
How it works: DateTimeImmutable modified +14 days to compute expiry date cleanly.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Calculate Event Expiration Date

  • PointCreate a DateTimeImmutable from "2026-01-01".
  • PointAdd 30 days using modify("+30 days").
  • PointPrint "Trial Ends: [Y-m-d]".
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates