Skip to content
AgileLogics
4 min read

Working with Dates and Times

Prerequisites: File I/O

The DateTime (and immutable DateTimeImmutable) classes handle dates properly — avoid raw Unix timestamps for anything beyond trivial cases.

$now = new DateTimeImmutable();
$birthday = DateTimeImmutable::createFromFormat('Y-m-d', '1990-05-15');

echo $now->format('Y-m-d H:i:s');
echo $now > $birthday ? 'Later' : 'Earlier';

$nextWeek = $now->modify('+7 days'); // returns a NEW instance

Common mistakes

  • Using DateTime (mutable) and being surprised when a shared instance changes unexpectedly elsewhere — prefer DateTimeImmutable, which always returns a new instance from modify() instead of mutating in place.