Course outline

PHP / Intermediate: objects, persistence, and tests / Lesson 14

Immutable times and offsets

Compare PHP DateTimeImmutable instants and retain modification results.

About 24 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Compare instants with explicit offsets.
  • Use DateTimeImmutable results deliberately.
  • Compare fixed instants and distinguish named-zone scheduling rules.
  • Validate parsed dates and retain immutable operation results.

Define the time contract

An instant, a local calendar time, and an elapsed duration answer different questions. DateTimeImmutable represents a date and time without mutating the existing instance when methods produce a changed value. Specify the intended time zone and input format at the boundary. A numeric offset alone does not contain the future transition rules of a named time zone.

Compare instants

Two clock readings with different offsets can identify the same instant. The first example constructs fixed values and compares their Unix timestamps, so it does not depend on the machine’s current clock or local zone. Keep a named zone separately when future local scheduling requires its rules. Converting an instant to UTC is useful for comparison but does not preserve the user’s regional scheduling intent by itself.

php Fixed time values
<?php
declare(strict_types=1);

$a = new DateTimeImmutable("2026-01-01T12:00:00+02:00");
$b = new DateTimeImmutable("2026-01-01T10:00:00+00:00");
var_export($a->getTimestamp() === $b->getTimestamp());
echo "\n";
Expected output
true

Both values represent the same instant.

Keep immutable results

DateTimeImmutable methods return a new object when applying a modification. The second example adds an hour and prints both fixed times, showing that the original remains unchanged. Capture the returned value; calling a method and discarding it does not update the old object. A calendar day in a named zone can differ from a fixed elapsed 24 hours near a clock transition.

php Fixed time values
<?php
declare(strict_types=1);

$start = new DateTimeImmutable("2026-01-01T10:00:00+00:00");
$end = $start->modify("+1 hour");
echo $start->format("H:i"), " ", $end->format("H:i"), "\n";
Expected output
10:00 11:00

The modification returns a new time and leaves the original unchanged.

Interpret local time

Parsing external dates requires a documented format, time zone, and error policy. A local time without an offset can be ambiguous or invalid at a transition; decide how the application handles such cases rather than relying on a server default. Check the parser result or exception appropriate to the API, and validate domain limits separately from syntactic validity.

Test time boundaries

Test equivalent instants with different offsets, an unchanged original after modification, malformed input, and any transition case the application supports. Use fixed values or an injected clock rather than waiting for real time. Verify both the stored instant and displayed local value when required. A passing UTC-only test does not establish correct recurring local scheduling.

Separate instant, local time and duration

An instant identifies a point on the timeline. A local calendar reading describes wall-clock fields in a zone, while an elapsed duration measures time between instants; these are related but different contracts. For an offset-bearing timestamp, subtract the offset from the local clock to obtain its UTC reading. Two different clock readings can therefore represent the same instant, and two equal local readings with different offsets can represent different instants. DateTimeImmutable stores a date-time value with timezone information and its timestamp can support a whole-second instant comparison for the examples here. If subsecond precision matters, compare it explicitly rather than assuming integer timestamps preserve it. A numeric offset describes that relationship at a particular time; it does not carry a named region’s future daylight-saving rules. Keep the user’s named zone and intended local schedule when those rules are part of the requirement.

Retain the returned value and trace ownership

DateTimeImmutable modification methods return a new value; they do not mutate the original instance. Assign the return when the next step should use it, and test the original and result separately. Discarding the result of modify can make a calculation appear unchanged even though the method returned a different object. setTimezone also returns a new representation: it can display the same instant in another zone without moving that instant. Distinguish this conversion from changing the local schedule or adding a duration. DateInterval and modify expressions represent operations with calendar and timezone semantics; specify the operation rather than assuming every “day” is always 86,400 elapsed seconds. A calendar-day recurrence needs a named zone and a policy for transitions, whereas an elapsed timer may need a fixed number of seconds. Neither a new object nor a formatted string alone proves that a scheduling policy is correct.

Validate format, warnings and domain limits

External time text needs an agreed format, zone, ambiguity policy and error result. DateTimeImmutable::createFromFormat can return false on failure, and parsing can also produce warnings for normalized but invalid calendar fields; inspect getLastErrors immediately after the relevant parse and handle both errors and warnings according to the contract. A successful-looking object is not sufficient proof that the input was an allowed calendar date. Use a reset directive where appropriate so omitted fields do not silently inherit the current date or time, and compare the resulting formatted value with the required input when exact round-trip validation is part of the policy. Check the method’s documented behavior on the supported version. After syntax validation, apply business limits independently, such as an appointment date not before an allowed start. Do not silently reinterpret an ambiguous or nonexistent local time without a documented transition decision.

Design for named-zone transitions

A named time zone is a rule set whose offset can change; a fixed +01:00 offset does not encode those transitions. Around a spring clock change, some local times may not occur; around an autumn change, a local time may occur twice. The application must choose whether to reject, ask for clarification or apply a documented rule, then verify the behavior against the intended timezone database and runtime. Do not infer a universal transition date from one region or assume the host’s current timezone database will never change. Fixed historical cases can demonstrate the difference between local calendar arithmetic and elapsed seconds, but label the zone, date and observed runtime. Store enough information for the product’s purpose: a UTC instant is useful for an executed event, while a future recurring local appointment also needs its named zone and transition policy. Formatting in UTC is not a substitute for those scheduling decisions.

Test boundaries with fixed evidence

Use fixed timestamps with explicit offsets or an injected clock so tests do not depend on the machine’s current time. For a comparison, assert the intended instant relationship and displayed representation separately. For an immutable modification, assert that the original remains unchanged and the returned value reflects the operation. Include malformed text, an invalid calendar date that produces a warning, a valid leap day and domain-range rejection when applicable. For named-zone scheduling, test representative gap and overlap cases under an explicit policy and record the timezone database and runtime; an example in UTC alone cannot establish correct recurrence. Distinguish local unit evidence from browser, database or distributed-clock integration. The examples here use PHP 8.3-compatible syntax with fixed synthetic values and were qualified on PHP 8.5.12 CLI using its installed timezone data. They do not claim execution on PHP 8.3 or any external service.

20 worked examples

1. Equivalent fixed offsets

Problem: Predict and explain this fixed synthetic PHP time result: Equivalent fixed offsets.

  1. Subtracting the three-hour offset maps 15:30 to 12:30 UTC.
  2. Both fixed values therefore have the same whole-second timestamp.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T15:30:00+03:00'); $b = new DateTimeImmutable('2024-06-01T12:30:00+00:00');
echo $a->getTimestamp() === $b->getTimestamp() ? "same\n" : "different\n";
Expected output
same

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces same.

Why this result follows: Subtracting the three-hour offset maps 15:30 to 12:30 UTC. Both fixed values therefore have the same whole-second timestamp.

2. Same clock different instant

Problem: Predict and explain this fixed synthetic PHP time result: Same clock different instant.

  1. The first reading corresponds to 10:00 UTC while the second is 12:00 UTC.
  2. Matching clock text alone does not mean the instants match.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T12:00:00+02:00'); $b = new DateTimeImmutable('2024-06-01T12:00:00+00:00');
echo $a->getTimestamp() === $b->getTimestamp() ? "same\n" : "different\n";
Expected output
different

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces different.

Why this result follows: The first reading corresponds to 10:00 UTC while the second is 12:00 UTC. Matching clock text alone does not mean the instants match.

3. Earlier and later

Problem: Predict and explain this fixed synthetic PHP time result: Earlier and later.

  1. Both fixed values use the same offset and date.
  2. The 08:00 instant precedes the 09:00 instant in this comparison.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T08:00:00+00:00'); $b = new DateTimeImmutable('2024-06-01T09:00:00+00:00');
echo $a < $b ? "earlier\n" : "not-earlier\n";
Expected output
earlier

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces earlier.

Why this result follows: Both fixed values use the same offset and date. The 08:00 instant precedes the 09:00 instant in this comparison.

4. Previous UTC date

Problem: Predict and explain this fixed synthetic PHP time result: Previous UTC date.

  1. Subtracting two hours from local 00:30 crosses into the previous date.
  2. The UTC representation is January 1 at 22:30 for this fixed instant.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-01-02T00:30:00+02:00');
echo $a->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i'), "\n";
Expected output
2024-01-01 22:30

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 2024-01-01 22:30.

Why this result follows: Subtracting two hours from local 00:30 crosses into the previous date. The UTC representation is January 1 at 22:30 for this fixed instant.

5. Next UTC date

Problem: Predict and explain this fixed synthetic PHP time result: Next UTC date.

  1. A negative three-hour offset means adding three hours to obtain UTC.
  2. The conversion crosses midnight into January 2.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-01-01T23:30:00-03:00');
echo $a->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i'), "\n";
Expected output
2024-01-02 02:30

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 2024-01-02 02:30.

Why this result follows: A negative three-hour offset means adding three hours to obtain UTC. The conversion crosses midnight into January 2.

6. Timezone conversion preserves instant

Problem: Predict and explain this fixed synthetic PHP time result: Timezone conversion preserves instant.

  1. The new representation displays three hours ahead of UTC.
  2. The timestamp comparison confirms that setTimezone did not move the instant.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T12:00:00+00:00'); $b = $a->setTimezone(new DateTimeZone('+03:00'));
echo $b->format('H:i P'), ' ', $a->getTimestamp() === $b->getTimestamp() ? "same\n" : "different\n";
Expected output
15:00 +03:00 same

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 15:00 +03:00 same.

Why this result follows: The new representation displays three hours ahead of UTC. The timestamp comparison confirms that setTimezone did not move the instant.

7. Immutable day change

Problem: Predict and explain this fixed synthetic PHP time result: Immutable day change.

  1. The returned value advances one calendar day into February.
  2. The original remains January 31 because the object is immutable.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-01-31T10:00:00+00:00'); $b = $a->modify('+1 day');
echo $a->format('Y-m-d'), ' ', $b->format('Y-m-d'), "\n";
Expected output
2024-01-31 2024-02-01

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 2024-01-31 2024-02-01.

Why this result follows: The returned value advances one calendar day into February. The original remains January 31 because the object is immutable.

8. Ignored modification result

Problem: Predict and explain this fixed synthetic PHP time result: Ignored modification result.

  1. modify returns a new value that the code stores but does not use.
  2. The original object therefore still formats as 10:00.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T10:00:00+00:00'); $ignored = $a->modify('+2 hours');
echo $a->format('H:i'), "\n";
Expected output
10:00

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 10:00.

Why this result follows: modify returns a new value that the code stores but does not use. The original object therefore still formats as 10:00.

9. Assigned modification

Problem: Predict and explain this fixed synthetic PHP time result: Assigned modification.

  1. The returned value is assigned to b after adding two hours.
  2. The original remains 10:00 while the new value is 12:00.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T10:00:00+00:00'); $b = $ignored = $a->modify('+2 hours');
echo $a->format('H:i'), ' ', $b->format('H:i'), "\n";
Expected output
10:00 12:00

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 10:00 12:00.

Why this result follows: The returned value is assigned to b after adding two hours. The original remains 10:00 while the new value is 12:00.

10. Subtract fixed interval

Problem: Predict and explain this fixed synthetic PHP time result: Subtract fixed interval.

  1. The interval specifies thirty minutes.
  2. Subtracting it from 10:00 UTC produces 09:30 in the new value.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T10:00:00+00:00'); $b = $a->sub(new DateInterval('PT30M'));
echo $b->format('H:i'), "\n";
Expected output
09:30

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 09:30.

Why this result follows: The interval specifies thirty minutes. Subtracting it from 10:00 UTC produces 09:30 in the new value.

11. Leap day valid

Problem: Predict and explain this fixed synthetic PHP time result: Leap day valid.

  1. The fixed input is a valid leap day for 2024.
  2. The parse returns a value with no reported warnings or errors in this runtime.
php Fixed synthetic PHP CLI time fixture
<?php
$d = DateTimeImmutable::createFromFormat('!Y-m-d', '2024-02-29', new DateTimeZone('UTC')); $errors = DateTimeImmutable::getLastErrors();
echo $d !== false && $errors === false ? $d->format('Y-m-d') . "\n" : "invalid\n";
Expected output
2024-02-29

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 2024-02-29.

Why this result follows: The fixed input is a valid leap day for 2024. The parse returns a value with no reported warnings or errors in this runtime.

12. Invalid calendar warning

Problem: Predict and explain this fixed synthetic PHP time result: Invalid calendar warning.

  1. February 30 is not a valid date in the stated calendar input.
  2. The parser can return a normalized object with a warning, so the policy rejects the warning.
php Fixed synthetic PHP CLI time fixture
<?php
$d = DateTimeImmutable::createFromFormat('!Y-m-d', '2024-02-30', new DateTimeZone('UTC')); $errors = DateTimeImmutable::getLastErrors();
echo $d !== false && $errors !== false && $errors['warning_count'] > 0 ? "reject-warning\n" : "other\n";
Expected output
reject-warning

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces reject-warning.

Why this result follows: February 30 is not a valid date in the stated calendar input. The parser can return a normalized object with a warning, so the policy rejects the warning.

13. Malformed parse

Problem: Predict and explain this fixed synthetic PHP time result: Malformed parse.

  1. The text does not match the requested date format.
  2. The false result is handled as a parse failure rather than used as an object.
php Fixed synthetic PHP CLI time fixture
<?php
$d = DateTimeImmutable::createFromFormat('!Y-m-d', 'not-a-date', new DateTimeZone('UTC'));
echo $d === false ? "invalid\n" : "parsed\n";
Expected output
invalid

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces invalid.

Why this result follows: The text does not match the requested date format. The false result is handled as a parse failure rather than used as an object.

14. Date-only reset

Problem: Predict and explain this fixed synthetic PHP time result: Date-only reset.

  1. The reset directive initializes unspecified time fields rather than inheriting the current clock.
  2. The fixed date formats at midnight UTC in this fixture.
php Fixed synthetic PHP CLI time fixture
<?php
$d = DateTimeImmutable::createFromFormat('!Y-m-d', '2024-04-05', new DateTimeZone('UTC'));
echo $d->format('Y-m-d H:i:s P'), "\n";
Expected output
2024-04-05 00:00:00 +00:00

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 2024-04-05 00:00:00 +00:00.

Why this result follows: The reset directive initializes unspecified time fields rather than inheriting the current clock. The fixed date formats at midnight UTC in this fixture.

15. Spring calendar day

Problem: Predict and explain this fixed synthetic PHP time result: Spring calendar day.

  1. The local calendar day crosses the London spring offset transition in this fixed 2024 fixture.
  2. Noon remains noon locally while 82,800 seconds elapse on the tested timezone data.
php Fixed synthetic PHP CLI time fixture
<?php
$z = new DateTimeZone('Europe/London'); $a = new DateTimeImmutable('2024-03-30 12:00:00', $z); $b = $a->modify('+1 day');
echo $b->format('Y-m-d H:i P'), ' ', ($b->getTimestamp() - $a->getTimestamp()), "\n";
Expected output
2024-03-31 12:00 +01:00 82800

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test. The tested host reports timezone_version_get() as 0.system and system tzdata package 2026e-0ubuntu0.24.04.1.

Expected result: The local fixture produces 2024-03-31 12:00 +01:00 82800.

Why this result follows: The local calendar day crosses the London spring offset transition in this fixed 2024 fixture. Noon remains noon locally while 82,800 seconds elapse on the tested timezone data.

16. Spring 24-hour interval

Problem: Predict and explain this fixed synthetic PHP time result: Spring 24-hour interval.

  1. The interval adds 24 elapsed hours across the same fixed London transition.
  2. The resulting local clock is 13:00 and the elapsed duration is 86,400 seconds.
php Fixed synthetic PHP CLI time fixture
<?php
$z = new DateTimeZone('Europe/London'); $a = new DateTimeImmutable('2024-03-30 12:00:00', $z); $b = $a->add(new DateInterval('PT24H'));
echo $b->format('Y-m-d H:i P'), ' ', ($b->getTimestamp() - $a->getTimestamp()), "\n";
Expected output
2024-03-31 13:00 +01:00 86400

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test. The tested host reports timezone_version_get() as 0.system and system tzdata package 2026e-0ubuntu0.24.04.1.

Expected result: The local fixture produces 2024-03-31 13:00 +01:00 86400.

Why this result follows: The interval adds 24 elapsed hours across the same fixed London transition. The resulting local clock is 13:00 and the elapsed duration is 86,400 seconds.

17. Autumn calendar day

Problem: Predict and explain this fixed synthetic PHP time result: Autumn calendar day.

  1. The fixed local day crosses London’s autumn offset transition in 2024.
  2. Noon stays noon locally while the tested timestamps differ by 90,000 seconds.
php Fixed synthetic PHP CLI time fixture
<?php
$z = new DateTimeZone('Europe/London'); $a = new DateTimeImmutable('2024-10-26 12:00:00', $z); $b = $a->modify('+1 day');
echo $b->format('Y-m-d H:i P'), ' ', ($b->getTimestamp() - $a->getTimestamp()), "\n";
Expected output
2024-10-27 12:00 +00:00 90000

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test. The tested host reports timezone_version_get() as 0.system and system tzdata package 2026e-0ubuntu0.24.04.1.

Expected result: The local fixture produces 2024-10-27 12:00 +00:00 90000.

Why this result follows: The fixed local day crosses London’s autumn offset transition in 2024. Noon stays noon locally while the tested timestamps differ by 90,000 seconds.

18. Fixed offset day

Problem: Predict and explain this fixed synthetic PHP time result: Fixed offset day.

  1. The fixed-offset fixture has no named-zone transition in this interval.
  2. Its one-day change spans 86,400 elapsed seconds for the stated values.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-03-30T12:00:00+00:00'); $b = $a->modify('+1 day');
echo ($b->getTimestamp() - $a->getTimestamp()), "\n";
Expected output
86400

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces 86400.

Why this result follows: The fixed-offset fixture has no named-zone transition in this interval. Its one-day change spans 86,400 elapsed seconds for the stated values.

19. Domain date boundary

Problem: Predict and explain this fixed synthetic PHP time result: Domain date boundary.

  1. The parsed fixed date precedes the synthetic earliest allowed instant.
  2. The domain comparison rejects it even though the date syntax itself is valid.
php Fixed synthetic PHP CLI time fixture
<?php
$date = new DateTimeImmutable('2024-04-04T00:00:00+00:00'); $earliest = new DateTimeImmutable('2024-04-05T00:00:00+00:00');
echo $date >= $earliest ? "accept\n" : "reject\n";
Expected output
reject

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces reject.

Why this result follows: The parsed fixed date precedes the synthetic earliest allowed instant. The domain comparison rejects it even though the date syntax itself is valid.

20. Subsecond limitation

Problem: Predict and explain this fixed synthetic PHP time result: Subsecond limitation.

  1. Both values lie in the same whole Unix second but have different microseconds.
  2. getTimestamp alone cannot establish equality at subsecond precision.
php Fixed synthetic PHP CLI time fixture
<?php
$a = new DateTimeImmutable('2024-06-01T12:00:00.100000+00:00'); $b = new DateTimeImmutable('2024-06-01T12:00:00.900000+00:00');
echo $a->getTimestamp() === $b->getTimestamp() ? "same-second\n" : "different-second\n";
Expected output
same-second

Qualified on PHP 8.5.12 CLI with its installed timezone data and fixed synthetic values; PHP 8.3-compatible syntax, not an 8.3 execution or external-service test.

Expected result: The local fixture produces same-second.

Why this result follows: Both values lie in the same whole Unix second but have different microseconds. getTimestamp alone cannot establish equality at subsecond precision.

Common errors and fixes

A modification appears to do nothing

Why it happens
The returned immutable object was discarded.
How to fix it
Store the returned value.
Prevent it next time
Test the original and new values.

Equivalent instants seem different

Why it happens
Local clock values have different offsets.
How to fix it
Compare their represented instants.
Prevent it next time
Record explicit offsets.

A recurring appointment shifts

Why it happens
A fixed offset was treated as a time-zone rule.
How to fix it
Use a named zone and a transition policy.
Prevent it next time
Test local transition cases.

20 practice exercises

1. Are 12:00 at +02:00 and 10:00 at +00:00 the same instant?

Show hint

Convert the local reading to a common instant.

Show worked solution

Yes. The first clock value corresponds to 10:00 UTC, matching the second.

Subtracting +02:00 from 12:00 yields 10:00 UTC, matching 10:00 at +00:00. The conclusion applies to the same calendar date in the fixture; keep the offset or zone context for interpretation.

Check your solution

  • Both values correspond to 10:00 UTC.
  • The comparison concerns an instant, not merely matching clock text.

2. Why assign the result of modify on DateTimeImmutable?

Show hint

An immutable modification returns a new object.

Show worked solution

It returns a new object; the original is not changed.

Assign the value returned by modify and compare both values: the original remains at its starting time while the returned instance reflects the change. Discarding that result does not update the original.

Check your solution

  • The original value remains unchanged.
  • The assigned result shows the requested modification.

3. Three event readings are 2024-06-01 18:15 +05:30, 12:45 +00:00 and 13:00 +00:00. Group equal instants and order the groups.

Show hint

Convert each reading to UTC before grouping.

Show worked solution

The +05:30 reading converts to 12:45 UTC, so it and the second reading are the same instant. Both precede the third reading at 13:00 UTC by 15 minutes. Preserve the date and offset context when presenting the original readings.

Check your solution

  • The first and second readings form one equal-instant group.
  • That group precedes the third by 15 minutes.

4. Three readings on the same date are 09:00 +02:00, 09:00 -01:00 and 10:00 +00:00. Order the instants and identify any equal pair.

Show hint

Convert all three readings to UTC before comparing.

Show worked solution

They convert to 07:00, 10:00 and 10:00 UTC respectively. The +02:00 event is three hours earlier; the -01:00 and +00:00 readings represent the same instant despite different local clock labels.

Check your solution

  • The first reading is earlier by three hours.
  • The second and third readings represent the same instant.

5. Event A is 2024-01-01 01:00 +03:00; event B is 2023-12-31 23:30 +00:00. Convert A to UTC, order them and calculate the gap.

Show hint

The offset conversion crosses the year boundary.

Show worked solution

Event A is 2023-12-31 22:00 UTC, while B is 23:30 UTC on that date. A precedes B by 90 minutes. Preserve the converted date and year as well as the clock time to avoid ordering the events incorrectly.

Check your solution

  • Event A is 2023-12-31 22:00 UTC.
  • Event B follows A by 90 minutes.

6. Starting at 08:00 UTC, assign the result of modify("+90 minutes") to a second variable, then subtract 30 minutes into a third. Predict all three displays.

Show hint

Each immutable operation returns a new value.

Show worked solution

The original stays 08:00, the second value is 09:30, and the third is 09:00. Capture each return and assert all three values; reusing or discarding the wrong result would lose the intended chain.

Check your solution

  • The original and second values are 08:00 and 09:30.
  • The third value is 09:00.

7. A value at 09:00 UTC is displayed at +03:00 using setTimezone. Define assertions for both display and instant.

Show hint

Changing representation is not adding elapsed time.

Show worked solution

Assert that the new representation displays 12:00 +03:00 and that its timestamp equals the original 09:00 UTC timestamp. Also assert the original object still displays 09:00, because the immutable method returns a new value.

Check your solution

  • The new local display is 12:00 +03:00.
  • The instant is unchanged and the original object remains 09:00 UTC.

8. A date parser accepts format Y-m-d in UTC. Compare 2024-02-29 and 2024-02-30 and specify how warnings affect acceptance.

Show hint

A returned object can coexist with a parsing warning.

Show worked solution

Accept the valid leap day only when parsing succeeds with no errors or warnings under this strict policy. Reject February 30 even if PHP normalizes it into another date and returns an object with a warning; inspect getLastErrors immediately.

Check your solution

  • 2024-02-29 is accepted without warnings.
  • 2024-02-30 is rejected when the warning is observed.

9. A date-only parser omits the reset directive and its output changes with the test execution time. Design a deterministic fixture and two assertions.

Show hint

Unspecified fields can inherit current values.

Show worked solution

Use an explicit UTC zone and an appropriate reset directive with fixed text, then assert both the requested date and the expected 00:00:00 time. Record parse errors and warnings immediately and avoid using the live current clock as an oracle.

Check your solution

  • The date matches the fixed input.
  • The time is 00:00:00 under the chosen reset policy.

10. A recurring meeting is at 12:00 Europe/London every local day. Explain why adding 86,400 seconds across a clock transition may violate the requirement.

Show hint

Local calendar recurrence and elapsed duration are different contracts.

Show worked solution

A fixed 86,400-second interval preserves elapsed duration, but an offset transition can shift the displayed local hour. Retain the named zone, define gap and overlap behavior, and test local occurrences around transitions using the intended timezone data.

Check your solution

  • The recurrence specifies a named zone and local hour.
  • Transition tests check both local display and elapsed interval.

11. A scheduler stores only +01:00 for a future regional appointment. Explain what rule information is missing and propose a fuller record.

Show hint

A fixed offset does not describe future regional transitions.

Show worked solution

Store the intended local date and time, the named time zone and a documented ambiguity policy, along with any resolved instant required by the application. A fixed offset can describe one instant but cannot alone reproduce future regional scheduling rules.

Check your solution

  • The named time zone and local schedule are retained.
  • Gap and overlap behavior is explicitly defined.

12. A local time occurs twice during an autumn transition. List the information needed before accepting an appointment and two possible policy choices.

Show hint

The same wall-clock fields may map to more than one instant.

Show worked solution

Record the named zone, local date and time, and which offset or occurrence the user intends when applicable. A product can reject ambiguity or ask for clarification, among other documented policies; test both occurrences on the intended timezone data rather than assuming one.

Check your solution

  • The zone and intended occurrence are explicit.
  • The chosen ambiguity policy is tested.

13. A spring transition makes a requested local time nonexistent. The product policy is to reject and ask for another time. Design acceptance checks without assuming PHP’s normalization is the policy.

Show hint

A parser result does not itself choose the product’s transition rule.

Show worked solution

Under the documented named-zone policy, identify the nonexistent local input and reject it with a safe correction message rather than silently accepting a normalized value. Test a valid nearby local time as a healthy control and record the timezone data used.

Check your solution

  • The nonexistent local time is rejected.
  • A nearby valid time is accepted under the same zone policy.

14. A timestamp pair differs only in microseconds .100000 and .900000 within the same second. Explain why getTimestamp equality is insufficient and propose an assertion.

Show hint

Whole seconds omit subsecond information.

Show worked solution

getTimestamp returns the same integer second for both values, but their microsecond fields differ. If the contract requires microsecond equality, compare the full precision or the relevant formatted fractional field along with the instant, and assert that this pair is different.

Check your solution

  • Whole-second timestamps are equal.
  • The full-precision comparison detects a difference.

15. A strict Y-m-d parser receives "2024-04-05extra" and "2024-04-05". Design an exact-input test including error handling and a deterministic timezone.

Show hint

Trailing data must not be silently accepted under an exact-format policy.

Show worked solution

Parse with the explicit reset format and UTC, inspect the return and getLastErrors immediately for each input, and require an exact formatted round trip. Reject the text with trailing data and accept the clean date only when there are no errors or warnings.

Check your solution

  • The trailing-data input is rejected.
  • The clean date is accepted as 2024-04-05 in the stated UTC policy.

16. An appointment parser accepts a syntactically valid date but the domain permits dates from 2024-04-05 onward. Compare April 4 and April 5.

Show hint

Syntax and domain limits are separate.

Show worked solution

Both dates can be valid calendar inputs, but April 4 violates the stated earliest date and is rejected. April 5 is the accepted inclusive boundary, assuming all other requirements pass; test the two cases independently.

Check your solution

  • April 4 is rejected by the domain rule.
  • April 5 is accepted at the inclusive boundary.

17. A fixed London spring-transition example shows local noon advancing one calendar day in 82,800 seconds. What evidence is needed before using that number for another year or zone?

Show hint

Transition rules are zone- and data-dependent.

Show worked solution

Do not generalize the single 2024 Europe/London fixture to another year or zone. Run fixed representative transition cases with the intended named zone and timezone database, record the runtime and observed offsets, and apply the product’s recurrence policy.

Check your solution

  • The 82,800-second result remains scoped to the original fixture.
  • The new zone and timezone data are tested and recorded.

18. A test compares two dates after modify but only asserts the new value. Add an assertion that verifies immutability and describe a failure it would catch.

Show hint

Check the starting object as well as the result.

Show worked solution

Record the fixed starting time, assign the returned modified object, and assert that the original still equals its starting representation while the new value equals the intended result. This catches an unintended mutation or a test that accidentally overwrote the original reference.

Check your solution

  • The original remains at its fixed starting value.
  • The returned value reflects the intended modification.

19. A local test passes on PHP 8.5.12 with system timezone data, but production uses a different PHP build and timezone database. Write a bounded conclusion and next check.

Show hint

A local pass is evidence for the environment actually tested.

Show worked solution

Report the fixed cases, actual PHP CLI version and timezone-data context, and state that production was not exercised. Run the relevant named-zone transition and parsing tests in an authorized isolated target-equivalent environment before claiming compatibility.

Check your solution

  • The local runtime and data scope are recorded.
  • Target-environment behavior remains unverified until tested.

20. A UTC-only test passes for a daily 09:00 regional meeting. Design a minimal named-zone test matrix that addresses both missing and repeated local times.

Show hint

A UTC clock has no evidence of the region’s transitions.

Show worked solution

Choose the intended named zone and representative spring gap and autumn overlap dates from its target timezone data. Test the documented reject or clarification policy for each, plus a normal day, and assert both local display and resolved instant when applicable.

Check your solution

  • The matrix includes gap, overlap and normal cases.
  • The product’s explicit policy and target data are recorded.

Key takeaways

  • Compare instants with explicit time-zone information.
  • Capture immutable modification results.
  • An offset is not a named zone’s future rule set.
  • Immutable modifications require using the returned value.
  • Parsing warnings and business limits require explicit checks.

Official references