PHP Functions Reference

PHP date() and DateTimeImmutable: Working with Dates

Format dates in PHP and work with immutable date objects, time zones, and predictable date calculations.

PHP date() and DateTimeImmutable

PHP offers date functions and date-time classes for formatting and manipulating dates. For application logic, DateTimeImmutable is often easier to reason about because operations return new objects rather than modifying the original.

Format the Current Date

echo date("Y-m-d H:i:s");

The output uses the default time zone configured for PHP. Configure the application's intended time zone explicitly rather than relying on an unknown server default.

Use DateTimeImmutable

$date = new DateTimeImmutable(
    "2026-11-21",
    new DateTimeZone("UTC")
);

$nextWeek = $date->modify("+7 days");

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

The original $date remains unchanged.

Parse and Handle Errors

For strict input formats, use DateTimeImmutable::createFromFormat() and inspect parsing errors. Do not assume arbitrary user-provided date strings are valid.

Store and Display Dates

A common approach is to store timestamps consistently (often UTC) and convert them to the viewer's intended time zone when displaying them. Be explicit about time zones, especially around daylight-saving transitions.

Summary

Use date() for straightforward formatting and DateTimeImmutable for more structured date calculations. Make time-zone assumptions explicit.

Share this page Help other developers discover this resource.