SyntaxStudy
Sign Up
PHP The DateTime Class
PHP Beginner 7 min read

The DateTime Class

The DateTime (and immutable DateTimeImmutable) class provides an object-oriented interface that is safer and more expressive than the procedural functions.

  • new DateTime() creates an object representing the current moment (or a parsed string).
  • format() uses the same format characters as date().
  • modify() accepts human-readable relative strings.

Prefer DateTimeImmutable — its modification methods return a new object instead of mutating the original, preventing subtle bugs.

Example
<?php
// Create from "now"
$now = new DateTimeImmutable();
echo $now->format('Y-m-d H:i:s');

// Create from a string
$birthday = new DateTimeImmutable('1990-06-15');
echo $birthday->format('l, F j, Y'); // Friday, June 15, 1990

// modify() returns NEW object (immutable)
$nextWeek  = $now->modify('+7 days');
$lastMonth = $now->modify('-1 month');
$nextYear  = $now->modify('+1 year');

echo $nextWeek->format('Y-m-d');
echo $lastMonth->format('Y-m-d');

// Create from a specific format
$d = DateTimeImmutable::createFromFormat('d/m/Y', '25/12/2024');
echo $d->format('Y-m-d'); // 2024-12-25

// Timestamps
$ts = $now->getTimestamp();
$fromTs = (new DateTimeImmutable())->setTimestamp($ts);
Pro Tip

Tip: Always prefer DateTimeImmutable over DateTime. Because mutations return a new instance, you can safely pass date objects to functions without worrying that they will alter the original value.