php-fechas-y-tiempo-en-php

Dates and Time in PHP

  • 2 min

DateTimeImmutable is a class for representing dates and times without accidentally modifying the original value.

In the old days, PHP used the date() and time() functions for everything. Although they still exist, they are limited: they handle time as simple strings or numbers (timestamps), which makes calculations (adding days, subtracting hours) or handling time zones complicated.

The modern and professional way is to use the DateTime class. It treats time as an intelligent object, not as a dumb text.

The problem of mutability (DateTime)

The standard DateTime class is mutable. This means that if you modify the object (for example, adding a day to it), the original object changes.

This can cause silent bugs if you pass that date to another function and that function modifies it without you knowing.

// Example with DateTime (Mutable)
$fecha = new DateTime('2023-01-01');

echo $fecha->format('Y-m-d'); // Output: 2023-01-01

// We modify the date
$fecha->modify('+1 month');

// WATCH OUT! The original variable $fecha has changed
echo $fecha->format('Y-m-d'); // Output: 2023-02-01
Copied!

The modern solution: DateTimeImmutable

To avoid accidents, modern PHP prefers DateTimeImmutable. As its name implies, it does not change. Every time you try to modify it, instead of altering the original, it returns a new copy with the change applied.

// Example with DateTimeImmutable (Recommended)
$fechaOriginal = new DateTimeImmutable('2023-01-01');

// We try to modify it, but store the result in ANOTHER variable
$fechaNueva = $fechaOriginal->modify('+1 month');

echo $fechaOriginal->format('Y-m-d'); // Output: 2023-01-01 (Unchanged!)
echo $fechaNueva->format('Y-m-d');    // Output: 2023-02-01 (The modified copy)
Copied!

Get used to always using DateTimeImmutable by default. It makes your code more predictable and prevents hard-to-track errors.

Common operations

Forget about manually calculating seconds. These objects have methods for everything:

A. Formatting (Displaying the date)

Instead of date(), you use the object’s ->format() method.

$ahora = new DateTimeImmutable();
echo $ahora->format('d/m/Y H:i:s'); // Ex: 25/10/2023 14:30:00
Copied!

B. Calculations (Add and Subtract)

You can use natural language in English.

$cita = new DateTimeImmutable('2023-10-01');
$vencimiento = $cita->modify('+2 weeks 3 days'); // Adds 2 weeks and 3 days
Copied!

C. Difference between dates (diff)

Calculates the exact time between two dates. Returns a DateInterval object.

$nacimiento = new DateTimeImmutable('1990-05-20');
$hoy = new DateTimeImmutable();

$diferencia = $nacimiento->diff($hoy);

echo "You are " . $diferencia->y . " years and " . $diferencia->m . " months old.";
Copied!

D. Time Zones (DateTimeZone)

Essential if your server is in one country and your users are in another.

// Create a date specifying the time zone
$zonaMadrid = new DateTimeZone('Europe/Madrid');
$fechaMadrid = new DateTimeImmutable('now', $zonaMadrid);
Copied!