Timezone Conversion Best Practices for Developers
Best practices for converting between timezones in software. Covers storage, transmission, display, and common pitfalls with practical code examples.
Development
Detailed Explanation
Timezone Conversion Best Practices
Correct timezone handling follows a simple three-layer architecture: store in UTC, convert at the boundary, display in local time.
The Golden Rule
User Input → Convert to UTC → Store/Transmit → Convert to Local → Display
(local time) (always UTC) (local time)
1. Store Everything in UTC
Your database, message queues, and log files should always use UTC:
-- PostgreSQL
CREATE TABLE events (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
starts_at TIMESTAMPTZ NOT NULL, -- Always stored as UTC
timezone TEXT NOT NULL -- IANA ID for display
);
INSERT INTO events (name, starts_at, timezone)
VALUES ('Team Standup', '2024-03-15T14:30:00Z', 'America/New_York');
2. Transmit with Explicit Offsets
API responses should include the UTC offset or use the Z suffix:
{
"event": {
"name": "Team Standup",
"startsAt": "2024-03-15T14:30:00Z",
"timezone": "America/New_York",
"localTime": "2024-03-15T10:30:00-04:00"
}
}
3. Convert at the Boundary
Only convert between UTC and local time at the point of user interaction:
// User selects a local time
const localInput = "2024-03-15T10:30"; // No timezone info
const userTimezone = "America/New_York";
// Convert to UTC for storage
const utcDate = new Date(
new Date(localInput).toLocaleString("en-US", { timeZone: "UTC" })
);
// Better: use a library
import { zonedTimeToUtc } from 'date-fns-tz';
const utcDate = zonedTimeToUtc(localInput, userTimezone);
4. Handle Edge Cases
- DST gaps: When clocks spring forward, some local times don't exist
- DST overlaps: When clocks fall back, some local times occur twice
- Timezone rule changes: Countries can change their timezone rules
- Half-hour offsets: Not all offsets are whole hours
5. Test Thoroughly
Write tests for:
- DST transition dates (both spring and fall)
- Midnight crossings in different timezones
- Dates near the International Date Line
- Leap years and month boundaries
- Half-hour and 45-minute offset timezones
Use Case
These best practices apply to virtually every software system that handles dates and times: web applications, mobile apps, APIs, background job schedulers, billing systems, analytics platforms, and reporting tools. Following these patterns prevents the most common timezone bugs that affect user experience and data integrity.