Store and compute in UTC, set date.timezone = UTC in php.ini, and convert to the reader’s zone exactly once — at the moment you render. PHP itself resolves the timezone from one place at a time: date_default_timezone_set() if your code called it, otherwise date.timezone from the loaded ini file, otherwise a UTC fallback you should never rely on. The bugs almost never come from that resolution order; they come from the layers around it. The CLI and PHP-FPM read different ini files, the database connection carries its own time_zone, and the operating system carries the tzdata rules underneath both. This page is about making those four agree, and about recognising each failure when only three of them do.
What you’ll accomplish
- Know which layer decides the timezone for any given line of PHP, and which setting controls it.
- Set
date.timezone = UTCwhere it is actually read — separately for PHP-FPM and for the CLI. - Pin the database connection’s session
time_zonefrom the application instead of inheritingSYSTEM. - Write date arithmetic that survives a DST transition, a tzdata update, and a serialization round trip.
- Read a wrong timestamp backwards to the layer that produced it, instead of guessing.
Prerequisites
- PHP 8.0 or later. The behaviour described here is stable across 8.0–8.4; older branches differed in how loudly they complained about a missing
date.timezone. - Root or ini-editing access on the server. On a plain Debian or Ubuntu box that means
/etc/php/8.3/fpm/php.iniand/etc/php/8.3/cli/php.ini. On RHEL-family systems it is a single/etc/php.inishared by both SAPIs, with FPM overrides in/etc/php-fpm.d/. On cPanel with EasyApache 4 every PHP version has its own tree under/opt/cpanel/ea-php8X/root/etc/, and CloudLinux PHP Selector accounts runalt-phpbuilds under/opt/alt/instead. - MySQL 5.7+ or MariaDB 10.3+ if you are following the database section, with an account allowed to read the
time_zonesystem variables. - A current
tzdatapackage on the host. PHP ships its own copy of the timezone database compiled into thedateextension, so PHP and the OS can hold different rules — the verification step below prints both. - Shared hosting caveat: if you cannot edit
php.ini, everything below still applies, but you will be doing it from application code withini_set('date.timezone', 'UTC')at bootstrap, which is strictly weaker.
Throughout, 8.3 stands for your PHP version and app for your database name.
How it works
A timestamp in a PHP application passes through four independent layers, and each one has a different owner and a different setting.
PHP’s resolution order is short. When any date function needs a default zone, PHP asks in this order: a zone set at runtime by date_default_timezone_set(), then the date.timezone directive from whichever ini files this SAPI parsed, then UTC as a last-resort fallback. The fallback is the trap. It is not a guarantee that your server behaves as UTC — it only applies when the directive is genuinely empty, and plenty of distributions, control panels and Docker base images set date.timezone for you to something regional. Relying on the fallback means your correctness depends on a file you never wrote and cannot see in your repository.
The two ini files are the single most common cause of “cron produces different timestamps than the web app”. PHP-FPM and the PHP CLI are separate SAPIs with separate configuration trees on Debian and Ubuntu. Setting date.timezone in one of them and restarting the pool feels like a fix, and the web app is fixed — but every cron job, every queue worker, every wp-cli invocation and every deploy script still reads the other file. Because both processes run the same application code, nothing in the codebase hints at the split. This is the same class of problem as a PHP CLI and FPM version mismatch, and it is diagnosed the same way: ask each binary what it loaded, rather than assuming.
The database connection has a timezone of its own. MySQL and MariaDB expose three variables: @@system_time_zone is what the server read from the OS at startup and is read-only; @@global.time_zone is the server default, usually the literal string SYSTEM, which means “defer to @@system_time_zone”; and @@session.time_zone is what your connection actually uses, inherited from the global value unless you set it. When the global value is SYSTEM, the database silently follows whatever /etc/localtime said at the moment mysqld started — including a value that has since been changed but not restarted into effect.
That session zone matters because of DATETIME versus TIMESTAMP. A DATETIME column stores the literal wall-clock string you gave it and hands it back unchanged; the session zone is irrelevant. A TIMESTAMP column stores seconds since the epoch: MySQL converts your value from the session zone on write and back into the session zone on read. If two connections have different session zones, they will read different wall-clock values out of the same TIMESTAMP row and neither will error. TIMESTAMP also tops out at 2038-01-19 03:14:07 UTC, which is close enough now to matter for subscription end dates and retention windows.
The display boundary is the only place a non-UTC zone belongs, and the zone you use there must be an IANA identifier — America/Toronto, not EST. An abbreviation cannot express DST: EST is a fixed −05:00 all year, so a value formatted with it will be an hour wrong for the eight months Toronto spends on EDT. Identifiers carry the whole rule history, including the dates on which offsets change.
Step-by-step
-
Ask each SAPI what it actually loaded. Do not assume the path; both binaries will tell you.
php --ini php-fpm8.3 --iniThe
Loaded Configuration Filelines will differ, and that difference is the whole problem:Loaded Configuration File: /etc/php/8.3/cli/php.ini Loaded Configuration File: /etc/php/8.3/fpm/php.ini -
Read the current value out of each one. The ini directive and the effective runtime value can disagree if something calls
ini_set(), so check both.php -i | grep '^date.timezone' php-fpm8.3 -i | grep '^date.timezone' php -r 'echo date_default_timezone_get(), PHP_EOL;'A directive that has never been set prints an empty local value, which is exactly the ambiguous state to eliminate:
date.timezone => no value => no value -
Set
date.timezone = UTCin both files. Same directive, two files, one restart each.; /etc/php/8.3/fpm/php.ini date.timezone = UTC; /etc/php/8.3/cli/php.ini date.timezone = UTCThen enforce it at the FPM pool level so that
ini_set()in application code and a stray.user.iniin a document root cannot quietly override it:; /etc/php/8.3/fpm/pool.d/www.conf php_admin_value[date.timezone] = UTCRestart rather than reload. A graceful reload drains existing workers, and a worker that started before the change keeps its old zone until it is recycled:
systemctl restart php8.3-fpm php-fpm8.3 -i | grep '^date.timezone'date.timezone => UTC => UTC -
Put the OS on UTC and keep tzdata current. The host layer feeds both the database’s
@@system_time_zoneand anything reading/etc/localtime.timedatectl set-timezone UTC timedatectl | grep 'Time zone' readlink -f /etc/localtimeTime zone: UTC (UTC, +0000) /usr/share/zoneinfo/UTCKeeping the clock itself correct is a separate job from keeping the zone rules correct — see Linux timezone and NTP with chrony for the synchronisation half. Update the rules with your package manager whenever a government changes them, and remember that PHP’s bundled copy is independent:
apt-get install --only-upgrade tzdata php -r 'echo timezone_version_get(), PHP_EOL;' -
Pin the database session zone from the application. Do not depend on
SYSTEM. Set the server default in the config file, and set the session value on every connection so a restarted or replicated server cannot drift underneath you.[mysqld] default-time-zone = '+00:00'$pdo = new PDO('mysql:host=127.0.0.1;dbname=app;charset=utf8mb4', $user, $pass, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET time_zone = '+00:00'", ]);MYSQL_ATTR_INIT_COMMANDruns on connect and on reconnect, which a one-off$pdo->exec()after construction does not. If you need named zones rather than numeric offsets —SET time_zone = 'America/Toronto'— the zone tables have to be populated first, or the statement fails with an unknown time zone error:mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql -
Use
DateTimeImmutable, and passDateTimeZoneexplicitly.DateTime::modify()mutates the object in place and returns$this, so any other variable, array entry or object property holding that same instance changes with it. That aliasing is the source of the classic “the end date moved when I calculated the start date” bug.DateTimeImmutablereturns a new instance from every operation and cannot be aliased.$tz = new DateTimeZone('America/Toronto'); $start = new DateTimeImmutable('2026-09-07 12:00:00', new DateTimeZone('UTC')); $end = $start->modify('+7 days'); echo $start->format(DateTimeInterface::ATOM), PHP_EOL; echo $end->setTimezone($tz)->format('Y-m-d H:i:s T'), PHP_EOL;2026-09-07T12:00:00+00:00 2026-09-14 08:00:00 EDT$startis untouched. Written withDateTime, the same three lines leave$startsitting a week in the future. -
Do calendar arithmetic in calendar units, never in seconds. Adding 86,400 seconds adds a fixed amount of elapsed time; adding one day adds a calendar day, which is 23 or 25 hours across a DST transition. Canada moves to DST on 8 March 2026:
$tz = new DateTimeZone('America/Toronto'); $day = new DateTimeImmutable('2026-03-07 12:00:00', $tz); echo $day->modify('+1 day')->format('Y-m-d H:i:s P'), PHP_EOL; echo $day->setTimestamp($day->getTimestamp() + 86400)->format('Y-m-d H:i:s P'), PHP_EOL;2026-03-08 12:00:00 -04:00 2026-03-08 13:00:00 -04:00Both lines are correct answers to different questions. “Tomorrow at noon” is the first one; “24 hours from now” is the second. Reservation systems, billing periods and digest emails almost always want the first.
-
Serialize with an offset at every boundary, and keep the zone if you need it. ISO 8601 through
DateTimeInterface::ATOMis the format to put in JSON, logs and queue payloads. But an offset is not a timezone:-04:00tells a consumer what the offset was at that instant, and nothing about what it will be next winter. For a value that must recur — a 09:00 daily report, a recurring booking — store the IANA identifier in its own column alongside the UTC instant, because only the identifier survives a rule change.
Validate it works
The point is to compare the four layers in one place, from the same process that is producing wrong values. Save this as tz-check.php and run it twice — once from the shell, once through the web server.
<?php
$pdo = new PDO('mysql:host=127.0.0.1;dbname=app;charset=utf8mb4', $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$db = $pdo->query('SELECT @@session.time_zone s, @@global.time_zone g, @@system_time_zone y')
->fetch(PDO::FETCH_ASSOC);
echo 'SAPI : ', PHP_SAPI, PHP_EOL;
echo 'OS zone : ', trim(shell_exec('date +%Z')), PHP_EOL;
echo 'PHP zone : ', date_default_timezone_get(), PHP_EOL;
echo 'DB session zone : ', $db['s'], ' (global ', $db['g'], ', system ', $db['y'], ')', PHP_EOL;
echo 'App assumes : ', getenv('APP_TIMEZONE') ?: '(unset)', PHP_EOL;
echo 'PHP tzdata : ', timezone_version_get(), PHP_EOL;
Run from the CLI, a correctly configured host prints:
SAPI : cli
OS zone : UTC
PHP zone : UTC
DB session zone : +00:00 (global +00:00, system UTC)
App assumes : UTC
PHP tzdata : 2026.1
Requested through the web server, only the first line should change, to fpm-fcgi. If shell_exec is disabled, drop that line and read the OS zone from readlink -f /etc/localtime separately. Finish with a round trip that proves the database is not converting behind your back:
mysql -u root -p -e "SELECT NOW(), UTC_TIMESTAMP(), @@session.time_zone;"
NOW() and UTC_TIMESTAMP() must be identical. If they differ, your session is not on UTC no matter what the ini files say.
Troubleshooting
Cron writes timestamps the web app cannot find. This is the two-ini-file split, and it is worth tracing once end to end because the symptom is silence rather than an error.
Both processes call the same function on the same instant and get answers four hours apart, so the cron job compares a stored 02:30 against its own idea of “now” at 22:30 the previous day, concludes the row is in the future, and skips it. Nothing logs. The fix is step 3 applied to both files; the diagnosis is step 1.
A WordPress plugin’s date() returns UTC while the dashboard shows local time. This is deliberate, not a misconfiguration. WordPress calls date_default_timezone_set('UTC') during bootstrap and keeps the site’s actual zone in its own options, readable through wp_timezone(). So inside WordPress, date() and time() are always UTC, current_time('mysql') returns site-local, and wp_date() is the function that formats an instant in the site’s zone with translated month names. A plugin that builds a “posts published today” query with date('Y-m-d') will use the wrong day for several hours every day in any zone west of UTC. Use wp_date() for anything a human reads and gmdate() for anything stored, and never call date_default_timezone_set() inside WordPress — it breaks the assumption core and every other plugin are built on.
strtotime() returns something plausible and wrong. Three traps recur. Relative months clamp rather than roll: strtotime('+1 month') on 31 January lands on 2 or 3 March, whereas strtotime('first day of next month') does what people mean. Weekday phrases are exclusive: strtotime('next Monday') evaluated on a Monday returns the following Monday. And a local wall-clock time that does not exist — 2026-03-08 02:30 in America/Toronto, inside the hour DST skips — will be silently normalised into 03:30. Parse with an explicit DateTimeImmutable and DateTimeZone and you at least control which zone the ambiguity is resolved in.
Times were right until a country changed its DST rules. Zone rules are data, not code, and they live in the tzdata package. An unpatched host keeps applying last year’s rules and will be an hour out for everyone in the affected region from the day the change takes effect. There are two copies to update: the OS package, and PHP’s own bundled database, which moves with the PHP point release. Compare timezone_version_get() in PHP against the OS package version and update whichever is behind.
A TIMESTAMP column reads back differently from two applications. Expected behaviour, given the definition: the column converts on write and on read using each connection’s session zone. Either pin every connection with step 5, or migrate the column to DATETIME and keep UTC values in it explicitly. Do not do the migration by simply changing the column type — dump the values through a CONVERT_TZ() expression so the stored numbers end up where you expect, and verify a known row before and after.
When this is the wrong approach
UTC everywhere is the right default, not a universal law. Two cases genuinely need the local zone stored alongside the instant. Scheduling is one: “every weekday at 09:00 Montreal time” cannot be represented by a UTC instant, because the correct UTC value changes twice a year — store the local time plus the IANA identifier and resolve to an instant at dispatch. Legal and financial records are the other: a transaction timestamp that must be evidenced in a specific jurisdiction’s civil time needs that civil time preserved as recorded, not reconstructed later from a rule set that may since have changed.
It is also the wrong first move when the symptom is an offset that is not a whole number of hours off, or that is inconsistent between rows written seconds apart. That points at a clock problem rather than a zone problem, and no amount of ini editing fixes a host whose time has drifted. Check NTP synchronisation first.
The PHP manual’s date and time section is the authority for the functions and the resolution order, and MySQL’s time zone support page covers the server variables and the zone tables. Timezone bugs are expensive to diagnose precisely because they produce plausible data instead of errors, and the four-value check above is worth running on every host before you need it.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.