How to Handle Timezones in Databases
Store timestamptz in UTC, convert at boundaries, keep future local events with their zone name, and test DST boundaries deliberately.
On this page
Introduction
Timezone bugs are the most predictable class of data corruption: they appear exactly twice a year in most regions, they misfire on international users immediately, and they are introduced by a single innocent decision, storing 2026-03-08 02:30 with no statement of what it means. The database layer is where the decision compounds, because every query, index, and aggregation inherits it. PostgreSQL gives two types that encode the two genuinely different meanings: timestamptz stores an instant, a point on the physical timeline, normalized to UTC internally; timestamp stores a wall-clock literal, a reading of a clock somewhere, with no claim about which timeline it is on. Almost every application bug in this space reduces to using the literal type for instants, or converting in the wrong layer. This tutorial fixes the type choice, pins session and driver configuration, pushes conversion to the presentation boundary, handles the future-events exception where local meaning matters more than the instant, and tests the DST boundaries where all of it breaks.
Two types, two meanings
The type choice is semantic, not stylistic. An instant is when something happened: the order was paid, the log line was emitted, the API was called. Instants belong in timestamptz, which stores an absolute moment and renders it in whatever session zone you ask for, correctly, everywhere. A wall-clock literal is what a clock read somewhere: the meeting is at 09:00, the report covers March, the cron runs at 02:30. Literals belong in timestamp, or better in explicit local-time-plus-zone columns, because their meaning is the reading itself, not a point on the timeline. The corruption pattern is instant-as-literal: a server in New York writes 2026-07-04 10:00 into a timestamp column, a server in Berlin reads it as ten o’clock local, and the data is now wrong by six hours with no error anywhere. The mirror bug, literal-as-instant, is rarer but nastier: a future meeting stored as a UTC instant jumps an hour when DST rules change, because 09:00 in Berlin in January and 09:00 in Berlin in July are different instants. The rule that prevents both: name the meaning, then pick the type.
Pin the session and driver
timestamptz values render in the session’s zone, and the session zone is set by server defaults, connection parameters, or driver configuration, which means the same value can display differently across environments. Determinism requires pinning it explicitly to UTC everywhere the application touches.
SET timezone = 'UTC';
Drivers carry the same knob: JDBC’s connection URL wants a timezone parameter, psycopg respects the TZ environment, and most ORM layers expose an explicit setting. Pin it in the connection factory, not in developer habit, so every environment, laptop, CI, staging, production, and every replica, agrees. One subtlety deserves respect: timestamptz does not store the zone. The zone is display context, applied at read time from the session; the stored value is always the UTC-normalized instant. Writing 2026-07-04 10:00+02 and reading it back in a UTC session gives 08:00, which is correct behavior and a frequent surprise in bug reports. The corollary is that timestamptz cannot answer what zone was this in, only when was it, which is why the future-events pattern in a later section carries the zone as data.
Convert at the boundary
The presentation layer, not the database, is where user-zone conversion belongs, because the zone is a property of the viewer, not of the fact. An order paid at a specific instant should store that instant once, in UTC, and render as 14:00 for a Berlin user and 08:00 for a New York user from the same column. Doing conversion in queries, casting to a session zone per report, bakes the viewer into the data pipeline and produces reports that disagree with each other by construction. The implementation rule: the API returns the instant in a canonical wire form, ISO 8601 with offset or epoch milliseconds, and the client formats with the user’s locale and zone, using proper timezone-aware libraries, Temporal in JavaScript, zone-aware datetime in Python, java.time in Java, never naive string manipulation. Aggregations by day are the boundary case that tempts database-side conversion, because day is zone-dependent: an orders-per-day chart for a Berlin user must bucket by Berlin days. The correct shape is still explicit: convert the instant to the user’s zone, then bucket the local component, either by shipping a user-zone parameter into the query with an AT TIME ZONE conversion, or by bucketing client-side from the canonical instants. What must never happen is bucketing by UTC days for a local-meaning chart, which quietly misfiles the six hours around midnight.
SELECT date_trunc('day', paid_at AT TIME ZONE $1) AS local_day,
count(*)
FROM orders
GROUP BY 1;
Future events keep their zone
Past events are instants and UTC serves them perfectly. Future events are commitments about local time, and the zone is part of the commitment: a flight departs at 09:00 local regardless of what the rules do between now and then. Storing the future instant alone, 09:00 Berlin converted to UTC now, breaks when the rules change, because the conversion used January’s rules for a July event, and the commitment shifts. The pattern that stays correct: store the local wall clock and the IANA zone name as data, and compute the instant on demand.
CREATE TABLE calendar_events (
id bigint PRIMARY KEY,
local_start timestamp NOT NULL,
zone_name text NOT NULL,
duration_minutes int NOT NULL
);
-- the instant, computed with current rules, for scheduling and alerts
SELECT local_start AT TIME ZONE zone_name AS start_instant
FROM calendar_events;
IANA zone names, Europe/Berlin rather than CET or plus-two, carry the rule history and future changes, so the computation picks up rule updates when the tz database is refreshed. Reminders and materialized schedules derived from these events must be recomputed when the tz data updates, which is an operational habit worth encoding: a scheduled job that recalculates pending derived instants after every timezone-database package upgrade. The offset column, plus-two, is the anti-pattern: it fixes one rule set into the row and cannot adapt.
Arithmetic across DST
Adding a day to an instant and adding a day to a wall clock are different operations, and confusing them produces off-by-one-hour bugs exactly on the two days a year anyone notices. Adding 24 hours to an instant is duration arithmetic: the result is exactly 24 hours later, which across a spring-forward night is 01:00 local on the wrong side of the shift. Adding a day to a local time is calendar arithmetic: 09:00 stays 09:00 the next local day, which is what humans mean by tomorrow at the same time. PostgreSQL’s interval arithmetic on timestamps follows the calendar interpretation, the + interval operation on a timestamphifts the wall clock; on timestamptz it shifts the instant by the stated duration. Choose by meaning: recurring schedules and human-facing tomorrow use calendar arithmetic on local values; timeouts, expirations, and SLAs use duration arithmetic on instants. The same distinction repeats at every granularity, months of differing length, years with leap days, and the libraries that survive are the ones that make the distinction explicit rather than guessing.
SELECT ts::timestamp + interval '1 day' AS next_local_day,
tstz + interval '24 hours' AS exactly_24h_later;
Test the boundaries
Timezone correctness fails only at boundaries, so tests must aim at them directly. DST transitions: for each zone the product serves, construct times one second before and after the spring-forward gap and the fall-back repeat, and assert storage round-trips and conversions behave, in particular that 02:30 on the nonexistent spring night maps somewhere defined and that the repeated 01:30 in fall disambiguates consistently. Zone-pin drift: run the storage round-trip with sessions in three different zones and assert identical stored instants. Aggregation alignment: generate orders clustered around local midnight in one user zone and assert the per-day bucket matches the user’s day, not UTC’s. Future-event rules: store an event across a not-yet-occurred DST change, advance the tz database or simulate the rule change, recompute, and assert the local commitment held. A fake clock plus a pinned tzdata version in CI keeps all of this deterministic, because tests that depend on the build machine’s current time and zone fail only in certain months, which is the flakiest possible failure mode.
const springGap = Temporal.PlainDateTime.from('2026-03-08T02:30:00');
// gap time: assert defined disambiguation strategy
const instant = springGap.toZonedDateTime('America/New_York', { disambiguation: 'reject' });
Common pitfalls
- Instants in timestamp columns. The value means whatever zone the writing session had; silent multi-hour corruption.
- Converting in the storage layer. User-zone rendering baked into data makes reports disagree by construction; convert at the boundary.
- Offsets as zone identity. plus-two fixes one rule set; IANA names carry rule history and future changes.
- UTC-day buckets for local-meaning charts. Six hours around midnight misfiled.
- Duration arithmetic for human schedules. 24 hours across a spring-forward night lands at the wrong local time; use calendar arithmetic on local values.
- Unpinned session zones. The same value renders differently per environment and per replica; pin UTC at the connection factory.
Conclusion
Timezone correctness is two type decisions and one layer decision. Store instants as timestamptz, normalized to UTC, with the session and driver timezone pinned so rendering is deterministic. Store future local events as local time plus an IANA zone name, because their commitment is the wall clock, and recompute derived instants when the rule data updates. Convert for the viewer at the presentation boundary, never in storage, and bucket by the user’s day when the day is the product’s meaning. Respect the split between duration arithmetic on instants and calendar arithmetic on wall clocks. Then test the transitions, gaps, repeats, and midnight clusters, with a pinned clock and tzdata, because those are the only days the bugs ever show up, and the only days anyone remembers the data being wrong.
Sources: PostgreSQL: date/time types, MDN: Temporal documentation, IANA time zone database.
FAQ
- What is the difference between timestamp and timestamptz?
- timestamp stores a wall-clock literal with no zone; timestamptz stores an absolute instant, normalized to UTC internally. The classic bug is storing an instant as timestamp: the value silently means whatever zone the session had.
- Why store UTC instead of the user’s timezone?
- UTC is the single canonical zone for instants. Users in different zones, servers in different locales, and DST transitions all read the same instant correctly when it is stored once in UTC and converted per viewer.
- Can I store offsets instead of zone names for future events?
- An offset like plus-two tells you the instant only if the rules stay fixed. IANA zone names like Europe/Berlin carry the rule history, so a future event keeps its local meaning even when the DST rules change.
Report a problem with this articleOpens a pre-filled issue on GitHub.