0PricingLogin
PHP Academy · Lesson

The DateTime Class

Create and manipulate dates with the object-oriented DateTime API.

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 object
  • DateTimeImmutable — 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');

All lessons in this course

  1. Unix Timestamps and date()
  2. The DateTime Class
  3. Date Arithmetic with DateInterval
  4. Timezones in PHP
← Back to PHP Academy