Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 147 ยท Advanced PHP

Dates and Times

Work with dates in PHP - date() and timestamps, strtotime, DateTimeImmutable, formats, DateInterval, DatePeriod, timezones, comparisons and DST pitfalls.

Dates look simple until you ship software to people in more than one country. Months have different lengths, clocks jump forward and back for daylight saving time (DST), "tomorrow" in Tokyo starts while it's still today in New York, and a user's "05/06/2026" might mean May 6 or June 5. PHP has a complete, well-tested date library built in. The trick is to use the right parts of it.

This lesson starts with the classic functions (time(), date(), mktime(), strtotime()) that you'll meet in every codebase, then moves to the object API that modern code should use: DateTimeImmutable, DateTimeZone, DateInterval and DatePeriod. Along the way you'll see the mistakes that cause real date bugs, and how to avoid them.

Our editor runs with date.timezone=UTC, so every example prints UTC unless it sets a timezone explicitly. Examples that use "now" print the moment you press Run, so your output will differ from anyone else's. Most examples use fixed dates so you can compare.

Timestamps and date()

A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC. It's a single integer with no timezone, which makes it easy to store and compare. time() returns the current one, and date($format, $timestamp) turns a timestamp into text in the default timezone:

PHP time(), date() and mktime()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The format string uses single letters for each part. Characters with no meaning are copied as is, and a backslash escapes a letter you want literally (that's why \a\t prints "at"). The most useful format characters:

Char Meaning Example
Y / y 4-digit / 2-digit year 2026 / 26
m / n Month with / without leading zero 07 / 7
d / j Day with / without leading zero 05 / 5
H / G 24-hour hour with / without zero 09 / 9
h / g 12-hour hour with / without zero 02 / 2
i / s Minutes / seconds 30 / 00
A / a AM/PM / am/pm PM
D / l Short / full weekday Mon / Monday
M / F Short / full month name Jul / July
N ISO weekday, 1 (Mon) to 7 (Sun) 1
t / L Days in month / leap year (1 or 0) 31 / 0
e / T / P Timezone ID / abbreviation / offset Europe/Paris / CEST / +02:00
U Unix timestamp 1784557800
c ISO 8601 date 2026-07-20T14:30:00+00:00

Month and day names are always English. For localized names ("juillet", "Juli") you'd use IntlDateFormatter from the intl extension, which our editor doesn't have, so it's not shown running here.

mktime() also normalizes out-of-range values instead of failing, so mktime(0, 0, 0, 7, 32, 2026) quietly becomes August 1. That's handy for date arithmetic but hides typos, which is why checkdate() exists for validating user-entered dates.

strtotime(): parsing English

strtotime() turns a description into a timestamp. It understands absolute dates and a surprising amount of relative English:

PHP Parsing dates with strtotime()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Always check for false: strtotime() returns it for text it can't parse, and date('...', false) would silently treat that as timestamp 0 (January 1, 1970). The flexibility is also a weakness for user input: strtotime() guesses formats, and 01/02/2026 is read as January 2 (US order) while 01-02-2026 is read as February 1. For input in a known format, use createFromFormat(), shown below.

DateTimeImmutable: the modern API

The classic functions work with bare integers and the global default timezone. The object API carries the timezone inside each value and gives you methods for arithmetic, comparison and formatting. There are two classes with almost the same methods:

  • DateTime is mutable: modify(), add() and setTime() change the object itself.
  • DateTimeImmutable returns a new object from every change and never alters the original.

Use DateTimeImmutable. Mutable dates cause a classic bug: you pass a date to a function, the function "calculates the due date" by modifying it, and your original date has moved too:

PHP DateTime versus DateTimeImmutable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With DateTime, the invoice date jumped to February 14 along with the due date. With DateTimeImmutable, the original stays put. Type-hint parameters as DateTimeInterface when you accept either, and return DateTimeImmutable from your own code.

format() uses the same characters as date(). PHP also defines constants for standard formats: DATE_ATOM (Y-m-d\TH:i:sP, the usual choice for APIs and JSON), DATE_RFC2822 for email headers, and DATE_COOKIE.

Parsing a known format

When you know the exact format of the input, such as a form field or a CSV column, createFromFormat() parses it strictly:

PHP Strict parsing with createFromFormat()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The round-trip check (format() the result and compare with the input) is the simplest way to reject impossible dates. Without it, 31/02/2026 would be accepted and silently become March 3, the same normalizing behavior as mktime(). The ! at the start of the format matters too: without it, fields you didn't parse (here the time) are filled in from the current moment, so two parses of the same string would produce different objects. The Form Validation lesson uses this function for date fields.

Intervals and differences

A DateInterval represents a duration such as "2 months and 3 days". You create one from an ISO 8601 duration string (P for period, T before time parts), add it with add() or subtract it with sub(), and get one back from diff():

PHP DateInterval and diff()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The month overflow line is one of the most common date bugs. There's no February 31, so +1 month from January 31 overflows into March. When you mean "same day next month, or the last day if it doesn't exist", use 'last day of next month' (for month-end dates) or clamp the day yourself.

From diff() you get the parts (y, m, d, h, i, s), the total number of days in days, and invert, which is 1 when the second date is earlier than the first. format() on an interval uses % codes: %y, %m, %d, %a (total days), %h, %i, %R (sign).

Repeating dates with DatePeriod

DatePeriod yields dates at a regular interval, which you loop over like an array. It's ideal for calendars, billing cycles and reports:

PHP Generating a schedule with DatePeriod

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The end date of a DatePeriod is exclusive by default (pass DatePeriod::INCLUDE_END_DATE to include it), and when you pass a number instead of an end date, it counts recurrences after the start, so 5 yields six dates in total. Since a DatePeriod is iterable, you can feed it to any function that accepts an iterable.

Timezones

A DateTimeImmutable always knows its timezone. You set it when creating the object, and setTimezone() converts to another zone: the moment stays the same, only the wall-clock display changes:

PHP Converting between timezones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Comparison operators work on date objects and compare moments, not wall-clock text, so $webinar == $tokyo is true even though one says 11:00 and the other 00:00 the next day. You can use <, >, == and the spaceship <=> (handy for usort(), as in Sorting Arrays). Don't use ===, which checks whether both variables are the very same object.

Always use region names such as Europe/Berlin rather than abbreviations like CET or fixed offsets like +01:00. A region name knows the area's DST rules and their history; an offset is right for only part of the year.

The rule that prevents most timezone bugs: store and compute in UTC, convert to the user's zone only for display. Save DATE_ATOM strings or UTC DATETIME values in your database, keep each user's preferred zone as a region name in their profile, and call setTimezone() in the view. Set date.timezone = UTC in production php.ini too, so nothing depends on the server's location.

DST pitfalls

Twice a year, many regions shift their clocks. In the EU in 2026, clocks jump from 02:00 to 03:00 on March 29 and fall back from 03:00 to 02:00 on October 25. That creates local times that don't exist and times that happen twice, and it means a "day" isn't always 24 hours:

PHP Daylight saving time surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The lessons from this output:

  • modify('+1 day') means "same time tomorrow", which is 12:00 even though only 23 hours passed. Surprisingly, modify('+24 hours') lands on 12:00 as well: in a zone with DST, modify() does its relative arithmetic on the local wall clock. When you mean elapsed time, use add(new DateInterval('PT24H')), do the math in UTC, or add seconds to a timestamp. All three give 13:00, exactly 24 real hours later.
  • Pick the one that matches your intent. A daily reminder at 09:00 wants +1 day; a 24-hour access token wants elapsed time (or simply timestamps).
  • Never compute days as seconds / 86400 in local time. Use diff()->days, which accounts for DST.
  • Scheduled jobs at 02:30 local time may run twice or not at all on change nights. Schedule in UTC, or avoid that hour.

Keeping all stored values and arithmetic in UTC, which has no DST, sidesteps nearly all of these problems.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is wrong with passing a DateTime object to a function that calls modify() on it?

    DateTime methods change the object itself, and objects are passed as handles. DateTimeImmutable returns a new object instead, so the caller's date is safe.
  2. 2. What does (new DateTimeImmutable('2026-01-31'))->modify('+1 month')->format('Y-m-d') print?

    February 31 does not exist in 2026, so PHP overflows 3 days into March. Use 'last day of next month' when you want the month's end.
  3. 3. A Berlin date is 2026-03-28 12:00, the day before clocks spring forward. What does ->add(new DateInterval('PT24H')) give?

    Adding a PT24H interval counts elapsed time, and the hour from 02:00 to 03:00 doesn't exist that night, so the wall clock shows 13:00. modify('+1 day') would keep 12:00.
  4. 4. Why should createFromFormat() results be checked with a round trip through format()?

    Out-of-range days and months overflow instead of failing. Formatting the result and comparing with the input catches those cases.
  5. 5. Two DateTimeImmutable objects describe the same moment in New York and Tokyo. What does $a == $b return?

    Comparison operators on date objects compare the underlying instant. Formatting differs, but the moment is the same.

Summary

  • A Unix timestamp counts seconds since 1970 UTC. time(), date(), mktime() and strtotime() work with timestamps and the default timezone; check strtotime() for false.
  • Prefer DateTimeImmutable: every change returns a new object. Accept DateTimeInterface in parameters.
  • format() and date() share format characters (Y-m-d H:i:s, D, F, N, P, c). Use DATE_ATOM for APIs.
  • Parse known formats with createFromFormat('!d/m/Y', ...) and verify with a round trip; PHP normalizes impossible dates silently.
  • DateInterval (P1M2DT3H) for durations, diff() for differences (days, invert), DatePeriod for repeating dates (end exclusive).
  • Watch month overflow: Jan 31 +1 month is March 3. Use last day of next month for month ends.
  • Store and compute in UTC with region-named timezones, convert for display with setTimezone(). Comparisons compare moments.
  • DST: modify() works on the local wall clock (+1 day and even +24 hours keep 12:00); add(new DateInterval('PT24H')), UTC math or timestamps count elapsed time. Some local times don't exist or happen twice.

Next: The PHP Type System in Depth