🎓 A1Learner
🔍
0 of 38 lessons completed

Dates in Depth

A date object is a value that holds a calendar date and can print or move it. PHP gives two date classes, and they differ in whether a move changes the object itself.

A fixed date prints in two patterns

new DateTime builds a date object from the fixed text 2026-01-15. format prints that date in two patterns.

<?php
$date = new DateTime("2026-01-15");
echo $date->format("Y-m-d") . "\n";
echo $date->format("D d M Y") . "\n";

modify changes the original DateTime

The date starts at 2026-01-15 here. The modify call moves it by 10 days, and the original prints the new date.

<?php
$date = new DateTime("2026-01-15");
echo $date->format("Y-m-d") . "\n";
$moved = $date->modify("+10 days");
echo $date->format("Y-m-d") . "\n";
echo $moved->format("Y-m-d") . "\n";

DateTimeImmutable leaves the original in place

The date starts at 2026-03-01 here. The modify call returns a moved copy, and the original still prints its first date.

<?php
$start = new DateTimeImmutable("2026-03-01");
$moved = $start->modify("+1 month");
echo $start->format("Y-m-d") . "\n";
echo $moved->format("Y-m-d") . "\n";

diff measures a fixed pair

diff compares the end date with the start date. The days value of the result prints as 30 days.

<?php
$start = new DateTime("2026-01-15");
$end = new DateTime("2026-02-14");
$diff = $start->diff($end);
echo $diff->days . " days\n";

Example

<?php
$start = new DateTimeImmutable("2026-05-10");
$end = $start->modify("+14 days");
echo "Start: " . $start->format("Y-m-d") . "\n";
echo "End: " . $end->format("Y-m-d") . "\n";
$diff = $start->diff($end);
echo "Length: " . $diff->days . " days\n";
echo "Start again: " . $start->format("Y-m-d") . "\n";

Key points

  • DateTime is the date class whose objects change when modify moves them.
  • DateTimeImmutable is the date class whose objects stay unchanged when modify moves them.
  • Use format to print a date with a pattern of letters.
  • The pattern Y-m-d prints a year, a month and a day with dashes.
  • Use modify to move a date by a stated amount of time.
  • The days part of a diff result holds the full count of days.

In this example, a DateTimeImmutable holds the start date 2026-05-10. modify builds the end date 14 days later without changing the start. diff measures 14 days between the two dates. The last line prints the start again to prove it stayed in place.

Note

Every date in this lesson is a fixed string, so every run prints the same lines.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A DateTime object is moved with modify. What happens to the original object?