DateTime Class & date())PHP provides robust date and time manipulation capabilities through procedural functions (like date(), strtotime(), time()) and the modern object-oriented DateTime, DateTimeImmutable, and DateInterval classes.
| Feature | date() / strtotime() |
DateTimeImmutable (Modern OOP) |
|---|---|---|
| Mutability | N/A (Functions) | Immutable (Prevents accidental side-effect state bugs) |
| Timezone Support | Global timezone state | Encapsulated per instance (DateTimeZone) |
| Date Arithmetic | strtotime("+1 week") (Strings) |
$dt->add(new DateInterval('P7D')) (Typed) |
Y: 4-digit year (2026).m: 2-digit month with leading zero (01 through 12).d: 2-digit day of month with leading zero (01 through 31).H: 24-hour hour format (00 through 23).i: Minutes (00 through 59).s: Seconds (00 through 59).flowchart TD
A["Create Date Object"] --> B["new DateTimeImmutable('now', new DateTimeZone('UTC'))"]
B --> C["Format Output: $dt->format('Y-m-d H:i:s')"]
B --> D["Date Arithmetic: $dt->modify('+30 days')"]
B --> E["Timezone Shift: $dt->setTimezone(new DateTimeZone('Asia/Dhaka'))"]
<?php
declare(strict_types=1);
// Set default fallback timezone
date_default_timezone_set('UTC');
// 1. Procedural Date Formatting
$currentTimestamp = time();
$formattedDate = date('Y-m-d H:i:s', $currentTimestamp);
// 2. Modern OOP DateTimeImmutable Usage
$now = new DateTimeImmutable('now', new DateTimeZone('UTC'));
$futureExpiration = $now->modify('+30 days');
// Timezone Conversion
$dhakaZone = new DateTimeZone('Asia/Dhaka');
$localTime = $now->setTimezone($dhakaZone);
echo "UTC Timestamp: " . $now->format('Y-m-d H:i:s T') . "
";
echo "Dhaka Local Time: " . $localTime->format('Y-m-d H:i:s T') . "
";
echo "Expiration Date (+30d): " . $futureExpiration->format('F j, Y') . "
";
DateTimeImmutable over DateTime: DateTimeImmutable methods return new instances when modified, preventing unexpected side-effect mutations.+00:00) and convert to local timezones during user presentation.date.timezone in php.ini or call date_default_timezone_set() at application bootstrapping.Create a DateTimeImmutable object for today's date, add 7 days using modify('+7 days'), and output it formatted as Y-m-d!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.