Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Date and time

A publication date, the end of a discount, a user's age — no site does without dates. PHP has the simple date() function and more powerful objects.

The current date

The date() function returns the current date in a given format. The letters in the format string are replaced with parts of the date:

<?php
 
$today = date('d.m.Y');
 
echo strlen($today); // 10

The result depends on the day you run it — 30.01.2025, for example.

Format letters

LetterMeaningExample
dDay with a leading zero05
mMonth with a leading zero01
YYear2025
HHours, 24-hour format14
iMinutes07
sSeconds30
NDay of the week, 1 is Monday4

A date object

For calculations the DateTimeImmutable object is handier. The constructor takes the date as a string:

<?php
 
$date = new DateTimeImmutable('2025-01-30 14:05');
 
echo $date->format('d.m.Y'), "\n"; // 30.01.2025
echo $date->format('H:i');         // 14:05

Without an argument the object holds the current moment.

Adding and subtracting

The modify() method shifts the date and returns a new object:

<?php
 
$date = new DateTimeImmutable('2025-01-30');
 
echo $date->modify('+7 days')->format('d.m.Y'), "\n";  // 06.02.2025
echo $date->modify('-1 month')->format('d.m.Y'), "\n"; // 30.12.2024
echo $date->modify('last day of this month')->format('d.m.Y'); // 31.01.2025

The original object does not change — that is what Immutable means.

The difference between dates

The diff() method returns the interval between two dates:

<?php
 
$start = new DateTimeImmutable('2025-01-01');
$finish = new DateTimeImmutable('2025-03-01');
 
$interval = $start->diff($finish);
 
echo $interval->days, "\n"; // 59
echo $interval->m;          // 2

The days property is the total number of days, m and d are months and days separately.

Comparing

Date objects are compared with the usual operators:

<?php
 
$deadline = new DateTimeImmutable('2025-06-01');
$now = new DateTimeImmutable('2025-05-20');
 
echo $now < $deadline ? 'There is still time' : 'The deadline has passed';

A date from user input

createFromFormat() parses a date in a known format and returns false if the string does not fit:

<?php
 
$date = DateTimeImmutable::createFromFormat('d.m.Y', '30.01.2025');
 
echo $date ? $date->format('Y-m-d') : 'Invalid date'; // 2025-01-30

Common mistake

PHP also has the DateTime class, and its methods change the object itself. A variable you thought of as the "start" changes silently:

<?php
 
$start = new DateTime('2025-01-30');
$finish = $start->modify('+1 day');
 
echo $start->format('d.m.Y'); // 31.01.2025 — the start changed too

Use DateTimeImmutable — it has no such surprises.

Thanks for reading!

Donate to the site — we work hard for you.