The DateTime Class
Create and manipulate dates with the object-oriented DateTime API.
The DateTime Class is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
DateTime vs Procedural Date Functions
PHP has both procedural functions (date(), strtotime()) and an OO DateTime API. The OO approach is preferred for complex operations:
DateTime— mutable date/time objectDateTimeImmutable— immutable (safer in modern code)
Creating DateTime Objects
Create DateTime objects from various inputs:
<?php
$now = new DateTime(); // current time
$specific = new DateTime('2024-12-25 14:30:00'); // from string
$fromTs = new DateTime('@' . time()); // from Unix timestamp
echo $now->format('Y-m-d H:i:s');
echo $specific->format('D, d M Y');
// DateTimeImmutable is safer:
$dt = new DateTimeImmutable('2024-01-01');Formatting with format()
Format a DateTime using the same format characters as date():
<?php
$dt = new DateTime('2024-05-27 14:30:00');
echo $dt->format('Y-m-d'); // 2024-05-27
echo $dt->format('H:i:s'); // 14:30:00
echo $dt->format('D d M Y, H:i'); // Mon 27 May 2024, 14:30
echo $dt->format('U'); // Unix timestamp
echo $dt->format(DateTime::ATOM); // ISO 8601modify()
Modify a DateTime with a relative expression:
<?php
$dt = new DateTime('2024-01-15');
$dt->modify('+1 month');
echo $dt->format('Y-m-d'); // 2024-02-15
$dt->modify('next Friday');
echo $dt->format('Y-m-d');
// DateTimeImmutable creates new object:
$dt2 = new DateTimeImmutable('2024-01-15');
$dt3 = $dt2->modify('+1 year'); // $dt2 unchangedcreateFromFormat()
Parse a date string with a specific format:
<?php
// Parse European date format
$dt = DateTime::createFromFormat('d/m/Y', '25/12/2024');
echo $dt->format('Y-m-d'); // 2024-12-25
// Parse with time
$dt2 = DateTime::createFromFormat('d.m.Y H:i', '27.05.2024 14:30');
echo $dt2->format('c'); // ISO 8601
// Returns false on failure:
$bad = DateTime::createFromFormat('Y-m-d', 'not-a-date');
var_dump($bad); // bool(false)Comparing DateTime Objects
Compare DateTime objects with comparison operators:
<?php
$a = new DateTime('2024-01-01');
$b = new DateTime('2024-12-31');
var_dump($a < $b); // true
var_dump($a == $b); // false
var_dump($a > $b); // false
// Sort an array of DateTime:
$dates = [new DateTime('2024-06-01'), new DateTime('2024-01-01')];
usort($dates, fn($a, $b) => $a <=> $b);
echo $dates[0]->format('Y-m-d'); // 2024-01-01getTimestamp()
Convert a DateTime to a Unix timestamp:
<?php
$dt = new DateTime('2024-12-25');
$ts = $dt->getTimestamp();
echo $ts; // Unix timestamp for Dec 25 2024
// setTimestamp()
$dt2 = new DateTime();
$dt2->setTimestamp($ts);
echo $dt2->format('Y-m-d'); // 2024-12-25Setting Date and Time Parts
Modify individual components of a DateTime:
<?php
$dt = new DateTime();
$dt->setDate(2024, 12, 25);
$dt->setTime(23, 59, 59);
echo $dt->format('Y-m-d H:i:s');
// 2024-12-25 23:59:59
// Or chain with DateTimeImmutable:
$dt = (new DateTimeImmutable())
->setDate(2024, 12, 25)
->setTime(0, 0, 0);DateTime in Practice: Subscription Check
Real-world use: check if a subscription is still active:
<?php
function isSubscriptionActive(string $expiresAt): bool {
$expiry = new DateTimeImmutable($expiresAt);
$now = new DateTimeImmutable();
return $expiry > $now;
}
var_dump(isSubscriptionActive('2025-12-31')); // true
var_dump(isSubscriptionActive('2020-01-01')); // falseCarbon Library
Carbon is a popular PHP library that extends DateTime with a fluent API:
<?php
// After: composer require nesbot/carbon
use Carbon\Carbon;
$now = Carbon::now();
$then = Carbon::parse('2024-01-01');
echo $now->diffForHumans($then); // '5 months after'
echo $now->addWeek()->format('Y-m-d');
echo Carbon::tomorrow()->isWeekday() ? 'weekday' : 'weekend';
// Locale-aware:
Carbon::setLocale('tr');
echo $now->diffForHumans($then); // TurkishISO 8601 and DateTime::ATOM
Use ISO 8601 format for APIs and databases:
<?php
$dt = new DateTime();
// ISO 8601
echo $dt->format('c'); // 2024-05-27T14:30:00+03:00
echo $dt->format(DateTime::ATOM); // same
echo $dt->format(DateTime::RFC3339); // same family
// For JSON APIs:
$json = json_encode([
'created_at' => $dt->format(DateTime::ATOM)
]);
echo $json;Quick Check
What is the key difference between DateTime and DateTimeImmutable?
Recap: The DateTime Class
DateTime OO essentials:
new DateTime('date string')to createformat()for outputmodify()for relative changescreateFromFormat()to parse custom formats- Prefer
DateTimeImmutableto avoid mutation bugs - Use ISO 8601 (
DateTime::ATOM) for APIs
Frequently asked questions
Is the “The DateTime Class” lesson free?
Yes — the full text of “The DateTime Class” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “The DateTime Class”?
Create and manipulate dates with the object-oriented DateTime API. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The DateTime Class” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.