PHP Dates and Times Quiz

PHP
0 Passed
0% acceptance

A 50-question quiz that sharpens instincts around PHP dates, timezones, formatting, parsing, scheduling windows, and daylight-saving pitfalls, with 20 hands-on code checks.

50 Questions
~100 minutes
1

Question 1

Release managers prefer UTC timestamps in logs even though dashboards render local time. Why?

A
UTC stays consistent across regions, simplifying correlation between systems and monitoring tools.
B
UTC automatically encrypts log entries.
C
Browsers reject non-UTC logs.
D
PHP cannot store non-UTC dates.
2

Question 2

What does this snippet echo?

php
<?php
      $dt = new DateTime('2025-05-01 10:00', new DateTimeZone('America/New_York'));
      $dt->setTimezone(new DateTimeZone('UTC'));
      echo $dt->format('H:i');
      ?>
A
14:00
B
10:00
C
UTC
D
Notice
3

Question 3

Why do teams prefer DateTimeImmutable in concurrent code paths?

A
Immutable instances force every change to return a new object, avoiding accidental shared-state mutations.
B
Immutable automatically caches results to disk.
C
Mutable DateTime cannot handle DST.
D
Immutable dates remove the need for timezones.
4

Question 4

What does this code print?

php
<?php
      $start = new DateTimeImmutable('2025-03-25 08:00', new DateTimeZone('UTC'));
      $next = $start->add(new DateInterval('PT36H'));
      echo $next->format('Y-m-d H:i');
      ?>
A
2025-03-26 20:00
B
2025-03-26 08:00
C
2025-03-27 08:00
D
Notice
5

Question 5

Why should engineers avoid storing raw strtotime input from users without validation?

A
strtotime accepts loose phrases that may parse differently per locale, so storing canonical values prevents drift and ambiguity.
B
strtotime always returns yesterday.
C
Users cannot enter strings longer than 10 characters.
D
Validation encrypts the date.
6

Question 6

What does this snippet output?

php
<?php
      echo date('Y-m-d', strtotime('first day of next month', strtotime('2025-01-18')));
      ?>
A
2025-02-01
B
2025-01-01
C
2025-12-01
D
Notice
7

Question 7

Why do billing systems convert user timezones to UTC before persisting invoice timestamps?

A
Applying a single reference timezone avoids DST-induced gaps when aggregating across customers.
B
UTC values compress better on disk.
C
SQL servers reject local times.
D
Browsers only understand UTC.
8

Question 8

What does this comparison echo?

php
<?php
      $a = new DateTime('2025-11-02 01:30', new DateTimeZone('America/New_York'));
      $b = clone $a;
      $b->add(new DateInterval('PT90M'));
      echo $b->format('H:i');
      ?>
A
02:00
B
03:00
C
04:00
D
Notice
9

Question 9

Why might DateTime::createFromFormat be preferred over strtotime when parsing user-provided ISO strings?

A
createFromFormat enforces an exact pattern and exposes detailed errors, avoiding silent reinterpretation.
B
strtotime cannot parse numbers.
C
createFromFormat automatically localizes output.
D
strtotime only runs on weekends.
10

Question 10

What does this snippet echo?

php
<?php
      $dt = DateTime::createFromFormat('Y-m-d H:i', '2025-04-15 09:45', new DateTimeZone('Europe/Paris'));
      echo $dt->format('c');
      ?>
A
2025-04-15T09:45:00+02:00
B
2025-04-15T07:45:00Z
C
2025-04-15 09:45 CET
D
Notice
11

Question 11

Why do daily digests use DatePeriod to iterate email windows?

A
DatePeriod pairs a start, interval, and end, producing reliable steps even through DST shifts.
B
DatePeriod sends emails automatically.
C
DatePeriod encrypts timestamps.
D
Loops cannot iterate without it.
12

Question 12

What does this snippet output?

php
<?php
      $period = new DatePeriod(
          new DateTime('2025-06-01'),
          new DateInterval('P1W'),
          3,
          DatePeriod::EXCLUDE_START_DATE
      );
      $count = 0;
      foreach ($period as $dt) {
          $count++;
      }
      echo $count;
      ?>
A
3
B
2
C
0
D
Notice
13

Question 13

Why do uptime monitors label timestamps with timezone abbreviations sparingly?

A
Abbreviations like EST or CST are ambiguous worldwide; explicit offsets or timezones reduce confusion.
B
Abbreviations cannot be printed in PHP.
C
Browsers ban abbreviations in JSON.
D
Offsets are encrypted when abbreviations appear.
14

Question 14

What result does this interval parsing yield?

php
<?php
      $interval = DateInterval::createFromDateString('2 weeks + 3 days');
      $start = new DateTimeImmutable('2025-02-10');
      echo $start->add($interval)->format('Y-m-d');
      ?>
A
2025-02-27
B
2025-02-24
C
2025-03-03
D
Notice
15

Question 15

Why does storing timestamps as integers ease comparison logic?

A
Unix timestamps let you compare or subtract values with simple arithmetic, independent of locale formatting.
B
Integers encrypt themselves.
C
Strings cannot represent times.
D
DateTime objects cannot be serialized.
16

Question 16

What does this snippet echo?

php
<?php
      $start = new DateTime('2025-01-01 00:00', new DateTimeZone('UTC'));
      $end = new DateTime('2025-01-31 23:59', new DateTimeZone('UTC'));
      $diff = $start->diff($end);
      echo $diff->days;
      ?>
A
30
B
31
C
0
D
Notice
17

Question 17

Why do APIs often return ISO 8601 strings (format("c")) instead of custom formats?

A
ISO 8601 is unambiguous, includes timezone offsets, and is widely supported by clients.
B
Custom formats are illegal in JSON.
C
ISO strings encrypt data.
D
format("c") is the only option PHP provides.
18

Question 18

What does this microtime snippet print?

php
<?php
      $start = microtime(true);
      usleep(50000);
      $elapsed = microtime(true) - $start;
      echo $elapsed > 0.04 && $elapsed < 0.1 ? 'window' : 'miss';
      ?>
A
window
B
miss
C
0.05
D
Notice
19

Question 19

Why should cron-driven PHP scripts pin their timezone via date_default_timezone_set at startup?

A
Explicitly setting the timezone avoids reliance on php.ini defaults that may differ between hosts.
B
Cron refuses to run without it.
C
Timezones change file permissions.
D
Setting the timezone encrypts log files.
20

Question 20

What does this formatting snippet echo?

php
<?php
      date_default_timezone_set('Asia/Jakarta');
      $dt = new DateTime('2025-08-17 07:30');
      echo $dt->format('l, d M Y H:i T');
      ?>
A
Sunday, 17 Aug 2025 07:30 WIB
B
Monday, 18 Aug 2025 00:30 UTC
C
Sunday, 17 Aug 2025 00:30 UTC
D
Notice
21

Question 21

Why do data pipelines prefer timestamp columns over storing formatted strings in data warehouses?

A
Numeric/temporal columns enable efficient range queries and timezone conversions downstream.
B
Strings cannot be stored in warehouses.
C
Formatted strings automatically expire.
D
Timestamp columns encrypt themselves.
22

Question 22

What does this DateTimeImmutable diff produce?

php
<?php
      $a = new DateTimeImmutable('2025-12-31 23:00', new DateTimeZone('UTC'));
      $b = $a->setTimezone(new DateTimeZone('America/Los_Angeles'));
      echo $b->format('Y-m-d H:i');
      ?>
A
2025-12-31 15:00
B
2025-12-31 23:00
C
2026-01-01 07:00
D
Notice
23

Question 23

Why should recurring reminders store the original timezone alongside the UTC timestamp?

A
Users expect events to follow their local DST shifts; retaining the source timezone lets you recalculate future fires correctly.
B
Timezones encrypt reminders.
C
UTC cannot represent recurring events.
D
Browsers require timezone names in JSON.
24

Question 24

What does this DateInterval formatting show?

php
<?php
      $start = new DateTime('2025-09-01 12:00');
      $end = new DateTime('2025-09-03 15:30');
      $diff = $start->diff($end);
      echo $diff->format('%a days %h hours %i minutes');
      ?>
A
2 days 3 hours 30 minutes
B
1 days 3 hours 30 minutes
C
3 days 0 hours 0 minutes
D
Notice
25

Question 25

Why do ingest pipelines reject timestamps without explicit timezone offsets?

A
Without an offset, the server must guess the timezone, which leads to inconsistent backfills.
B
Offsets increase file size dramatically.
C
Timestamps without offsets cannot be parsed.
D
Offsets are required only for leap years.
26

Question 26

What does this gmdate snippet echo?

php
<?php
      date_default_timezone_set('America/Sao_Paulo');
      echo gmdate('Y-m-d H:i', strtotime('2025-02-05 12:00'));
      ?>
A
2025-02-05 15:00
B
2025-02-05 12:00
C
2025-02-05 09:00
D
Notice
27

Question 27

Why do countdown timers rely on monotonic clocks (hrtime) when possible?

A
Monotonic clocks are not affected by manual clock changes or NTP adjustments, keeping durations stable.
B
hrtime encrypts results.
C
DateTime cannot measure durations.
D
Monotonic clocks automatically emit events.
28

Question 28

What does this DateTime comparison output?

php
<?php
      $a = new DateTime('2025-07-01 10:00 UTC');
      $b = new DateTime('2025-07-01 05:00-0500');
      echo $a <=> $b;
      ?>
A
0
B
1
C
-1
D
Notice
29

Question 29

Why do workflows store both created_at and updated_at timestamps even if they look identical initially?

A
Having both fields allows auditing of future edits and simplifies cache invalidation logic.
B
Databases refuse to save a single timestamp.
C
Frameworks crash without duplicate columns.
D
It halves the storage cost.
30

Question 30

What does this intl formatter produce?

php
<?php
      $formatter = new IntlDateFormatter(
          'de_DE',
          IntlDateFormatter::FULL,
          IntlDateFormatter::SHORT,
          'Europe/Berlin',
          IntlDateFormatter::GREGORIAN
      );
      echo $formatter->format(new DateTime('2025-12-24 18:45', new DateTimeZone('Europe/Berlin')));
      ?>
A
Mittwoch, 24. Dezember 2025 um 18:45
B
Wednesday, December 24, 2025 at 6:45 PM
C
24/12/2025 18:45
D
Notice
31

Question 31

Why should you avoid caching DateTime objects with serialized timezone rules across PHP upgrades?

A
Timezone database updates can change offsets, so cached objects created under an old tzdata version may go stale.
B
Serialization deletes timezones.
C
PHP cannot unserialize objects.
D
Caching always re-parses tzdata.
32

Question 32

What does this strtotime edge case echo?

php
<?php
      date_default_timezone_set('America/Sao_Paulo');
      echo date('H:i', strtotime('2025-10-19 01:30 +1 hour'));
      ?>
A
02:30
B
03:30
C
01:30
D
Notice
33

Question 33

Why do ETL jobs prefer storing milliseconds or microseconds when precision matters?

A
Sub-second precision keeps event ordering accurate for rapid-fire telemetry.
B
Whole seconds cannot be stored in SQL.
C
High precision timestamps are smaller.
D
Microseconds encrypt themselves.
34

Question 34

What does this leap-year snippet echo?

php
<?php
      $dt = new DateTime('2024-02-29');
      $dt->add(new DateInterval('P1Y'));
      echo $dt->format('Y-m-d');
      ?>
A
2025-03-01
B
2025-02-28
C
2024-02-29
D
Notice
35

Question 35

Why do SLA monitors store both the exact timestamp and an indexed day bucket?

A
Day buckets accelerate reports, while exact times allow precise audits and penalty calculations.
B
Day buckets encrypt timestamps.
C
Exact times cannot be queried.
D
Buckets replace the need for timezone metadata.
36

Question 36

What does this DatePeriod range output?

php
<?php
      $period = new DatePeriod(
          new DateTime('2025-01-01'),
          new DateInterval('P1M'),
          new DateTime('2025-04-01')
      );
      $labels = [];
      foreach ($period as $dt) {
          $labels[] = $dt->format('M');
      }
      echo implode(',', $labels);
      ?>
A
Jan,Feb,Mar
B
Jan,Feb,Mar,Apr
C
Feb,Mar
D
Notice
37

Question 37

Why might a team choose Carbon or other wrappers instead of raw DateTime in large apps?

A
Wrappers add fluent APIs, localization helpers, and testing conveniences while building on top of PHP’s core classes.
B
DateTime cannot handle localization.
C
Wrappers run faster because they bypass PHP.
D
DateTime is deprecated.
38

Question 38

What does this timezone list snippet echo?

php
<?php
      $tz = new DateTimeZone('Asia/Tokyo');
      echo $tz->getOffset(new DateTime('2025-07-01')) / 3600;
      ?>
A
9
B
8
C
0
D
Notice
39

Question 39

Why do data retention policies often reference both created_at and deleted_at when computing lifetimes?

A
Some objects exist for months before deletion; tracking both boundaries makes it easy to enforce retention windows.
B
Databases require two timestamps per row.
C
deleted_at holds encryption keys.
D
created_at cannot be timestamped.
40

Question 40

What does this sleep-based timer echo?

php
<?php
      $start = new DateTimeImmutable();
      sleep(2);
      $elapsed = $start->diff(new DateTimeImmutable());
      echo $elapsed->s >= 2 ? 'ok' : 'short';
      ?>
A
ok
B
short
C
2
D
Notice
41

Question 41

Why do compliance teams require documenting timezone assumptions for exports shared with partners?

A
Partners need to know whether timestamps are UTC, local, or offset-encoded to reconcile records accurately.
B
Timezone documentation encrypts spreadsheets.
C
Partners cannot convert timezones themselves.
D
Exports fail without documentation.
42

Question 42

Why do traffic dashboards aggregate metrics in rolling 15-minute windows instead of per-second?

A
Time buckets smooth spikes and reduce query costs while still exposing actionable trends.
B
Per-second data is illegal.
C
Dashboards cannot show seconds.
D
Buckets encrypt the data.
43

Question 43

Why do backend services log both request received time and completion time?

A
Capturing both boundaries supports latency analysis and helps correlate incidents when queues back up.
B
Completion time alone includes everything.
C
It is required for TLS handshakes.
D
Logs cannot store single timestamps.
44

Question 44

Why should scheduler tables avoid storing “every Monday” strings and instead normalize to cron expressions or rule sets?

A
Normalized rules are machine-readable, versionable, and easier to evaluate than free-form strings.
B
Strings cannot describe recurring events.
C
Cron expressions encrypt jobs.
D
Rule sets eliminate the need for validation.
45

Question 45

Why do observability tools convert timestamps to epoch nanoseconds before sending over the wire?

A
Packed integers reduce payload size and avoid formatting ambiguities, while preserving ordering.
B
Nanoseconds are required for HTTPS.
C
Strings cannot cross network boundaries.
D
Epoch numbers encrypt themselves.
46

Question 46

Why do QA teams test notifications around DST transitions twice per year?

A
Transitions introduce skipped or duplicated hours, which can cause duplicate sends or missed reminders if not handled.
B
DST changes encrypt emails.
C
It is legally required in every country.
D
Cron jobs pause automatically during DST.
47

Question 47

Why is it risky to assume all partners use Gregorian calendars?

A
Some regions follow fiscal or cultural calendars that start on different days or months, impacting reporting alignment.
B
Non-Gregorian calendars cannot be represented in JSON.
C
PHP cannot format Gregorian dates.
D
Partners reject timestamps with months.
48

Question 48

Why do cache keys often include rounded timestamps (e.g., minute resolution) instead of raw now() values?

A
Rounding keeps keys stable within a window, avoiding cache misses for data that can be reused briefly.
B
Caches refuse raw timestamps.
C
Rounded timestamps encrypt responses.
D
now() returns null.
49

Question 49

Why should retention jobs respect a grace period when deleting records based on deleted_at?

A
Grace periods allow for restoration if a deletion was accidental and ensure downstream systems have processed the change.
B
deleted_at cannot be trusted otherwise.
C
Grace periods encrypt archives.
D
Without grace periods, SQL fails.
50

Question 50

Why do architectural guidelines recommend central services for timezone conversions instead of scattering ad-hoc logic?

A
Centralized utilities consolidate tzdata updates, auditing, and testing, reducing the chance each team handles offsets differently.
B
Only single services can call DateTime.
C
Decentralized logic cannot import DateInterval.
D
Central services encrypt cookies.

QUIZZES IN PHP