PHP Tutorial · PHP for the Web · Lesson 26 of 38

PHP Date and Time

Format dates, do date arithmetic and handle time zones.

date()

date(format, timestamp) formats a Unix timestamp. Common format characters: Y year, m month, d day, H:i:s time, D/l weekday, M/F month name.

Example 1Try it yourself
<?php
$ts = mktime(14, 30, 0, 7, 4, 2026);   // 4 July 2026, 14:30
echo date("Y-m-d H:i", $ts), "\n";
echo date("l, F jS Y", $ts), "\n";
echo date("D d/m/y", $ts), "\n";

Output

2026-07-04 14:30
Saturday, July 4th 2026
Sat 04/07/26

DateTimeImmutable

For real work, use DateTimeImmutable — methods return new objects instead of changing the original, and time zones are explicit:

Example 2Try it yourself
<?php
$start = new DateTimeImmutable("2026-01-31 09:00", new DateTimeZone("UTC"));
$nextWeek = $start->modify("+7 days");
$inTokyo = $start->setTimezone(new DateTimeZone("Asia/Tokyo"));
echo $start->format("Y-m-d H:i T"), "\n";
echo $nextWeek->format("Y-m-d"), "\n";
echo $inTokyo->format("Y-m-d H:i T"), "\n";
echo $start->add(new DateInterval("P1M"))->format("Y-m-d"), "\n";

Output

2026-01-31 09:00 UTC
2026-02-07
2026-01-31 18:00 JST
2026-03-03

Notice the last line: adding one month to 31 January gives 3 March, because "31 February" overflows. Use modify("last day of next month") when you mean the end of the month.

Differences

Example 3Try it yourself
<?php
$a = new DateTimeImmutable("2026-01-01");
$b = new DateTimeImmutable("2026-12-25");
$diff = $a->diff($b);
echo $diff->days, " days\n";
echo $diff->format("%m months and %d days"), "\n";

Output

358 days
11 months and 24 days

Always set a time zone (date.timezone in php.ini or new DateTimeZone(...)). Store times in UTC and convert for display.

Test yourself

Which class returns a new object when you call modify()?

  1. DateTime
  2. DateTimeImmutable
  3. DateInterval
  4. Carbon
Show answer

Answer: DateTimeImmutable