ゆるテックノート

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.