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 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');