Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

DateTime

A mutable date and time object.

Syntax

new DateTime(string $datetime = "now", ?DateTimeZone $timezone = null)

Parameters

ParameterTypeDescription
$datetimestringOptional. The date as a string.
$timezone?DateTimeZoneOptional. The time zone.

Return value

DateTimeAn object with the `format()`, `modify()`, `diff()` and `setDate()` methods.

Examples

Creating and formatting:

<?php
 
$date = new DateTime('2026-03-15 10:30');
 
echo $date->format('d.m.Y H:i');

Output:

15.03.2026 10:30

The modify() method changes the object itself:

<?php
 
$start = new DateTime('2026-01-31');
$end = $start;
$end->modify('+1 day');
 
echo $start->format('Y-m-d');

Output:

2026-02-01

Notes

In the second example $start changed too: both variables point to one object. To avoid such surprises use DateTimeImmutable.

See also

  • DateTimeImmutable — A date and time object that cannot be changed: every operation returns a new object.
  • DateInterval — A span of time: days, months, hours.
  • date — Formats a date and time.

In the tutorial

  • Date and time — Working with dates in PHP — the date function, the DateTimeImmutable class, formats, adding to dates and the difference between them.

Thanks for reading!

Donate to the site — we work hard for you.