Handling Dates and Times Correctly in PHP

PHP’s DateTime classes replaced the old Unix-timestamp-and-date() approach, adding proper timezone handling and object-oriented date arithmetic — worth using even for simple date logic.

$now = new DateTimeImmutable('now', new DateTimeZone('Europe/Berlin'));

$nextWeek = $now->add(new DateInterval('P7D'));
$formatted = $now->format('Y-m-d H:i:s');

$diff = $nextWeek->diff($now);
echo $diff->days . " days difference\n";

// Parsing user input safely
$userDate = DateTimeImmutable::createFromFormat('d.m.Y', '25.12.2025');
if ($userDate === false) {
    echo "Invalid date format\n";
}

Always Prefer DateTimeImmutable

DateTime is mutable — calling ->add() modifies the original object, a classic source of subtle bugs when the same object is reused. DateTimeImmutable returns a new instance instead, which is almost always what you actually want.