Unix Time and Time Zones
Unix time is always UTC-based seconds, but teams often diverge on how to store, display, and log timestamps. This page summarizes practical policies and pitfalls.
๐ Separate UTC Storage from Local Display
Store in UTC; apply a local time zone only when showing it to humans.
Key points
- โ Unix time is always UTC-based; local time only appears at display time.
- โ Backends/DB should stick to UTC to avoid DST or offset issues.
- โ UI, emails, and reports apply the userโs time zone on output.
๐๏ธ Storage, APIs, and Logs
Decide where the time zone is applied and how you communicate it.
Database
- ๐พ Store UTC as integer Unix seconds/milliseconds, or use `timestamp with time zone` pinned to UTC.
- ๐พ Avoid putting local time into `timestamp without time zone`โit becomes ambiguous later.
APIs/messages
- ๐ Return ISO8601 with offset (e.g., `2024-02-29T12:00:00+09:00`).
- ๐ If returning integers, document the unit (sec/ms) and that values are UTC-based.
Logs/monitoring
- ๐ Prefer UTC for analysis, or emit both UTC and local.
- ๐ Include the time zone in the log format (`Z` or `+09:00`).
๐ง Conversion Examples
Explicit TZ settings reduce surprises from environment defaults.
Shell
- ๐ป `TZ=Asia/Tokyo date -d @1735689600 +"%Y-%m-%d %H:%M:%S %Z"` # show as JST
- ๐ป `date -u -d @1735689600 +"%Y-%m-%dT%H:%M:%SZ"` # show as UTC
In applications
- ๐งญ When parsing, respect the offset in the input and normalize internally to UTC.
- ๐งญ When rendering, apply the userโs time zone (Intl API on the web, user setting on backend).
โ ๏ธ Common Pitfalls
Default TZ mismatches, DST, and vague string parsing frequently bite teams.
Watch out for
- ๐ง Assuming the OS/container TZ is UTC when it is actually local (or vice versa); set it explicitly during image build.
- ๐ง DST regions have days shorter/longer than 24h; naive addition/subtraction can drift.
- ๐ง Parsing timezone-less datetime strings falls back to the environmentโs default TZ.
- ๐ง Browser and server using different TZs can render the same Unix second as different local times.
๐งช Testing and Operations
Run checks with different TZ settings to ensure consistent behavior.
Checklist
- ๐ Verify the same Unix second renders as expected in both UTC and local (e.g., JST).
- ๐ Test DST-crossing data (e.g., `America/New_York`) for addition/subtraction correctness.
- ๐ Validate inputs to reject timezone-less datetimes where an offset is required.