ใ‚†ใ‚‹ใƒ†ใƒƒใ‚ฏใƒŽใƒผใƒˆ

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.