跳到主要内容
uencoder

如何Convert Timestamps

转换 between Unix timestamps, ISO 8601 strings, and human-readable date formats.

问题

你有 时间戳在 one 格式化 (e.g., Unix epoch) 和 need 它在 另一个 (e.g., ISO 8601 或本地时间).

前置条件

  • Understanding 的 Unix timestamps
  • Knowledge 的 ISO 8601 格式化

步骤

  1. 1. Identify the input format

    Determine whether the timestamp is a Unix epoch (seconds or milliseconds since 1970-01-01), an ISO 8601 string, or a custom format. Unix timestamps in seconds are 10 digits; milliseconds are 13 digits. This distinction is critical.

    输入
    1697254800 (seconds)
    输出
    Unix epoch in seconds
  2. 2. Convert to the target format

    Parse the timestamp into a date object, then format it as needed. For ISO 8601, use toISOString(). For human-readable, use locale-aware formatting. For Unix timestamp, use getTime()/1000 (seconds) or getTime() (milliseconds).

    输入
    1697254800 → ISO 8601
    输出
    2023-10-14T03:00:00.000Z
  3. 3. Handle timezones correctly

    Unix timestamps are always UTC. When displaying in local time, convert explicitly. Beware of the system's local timezone affecting parsing of date strings. Always store and transmit timestamps in UTC to avoid ambiguity.

    输入
    UTC → local time
    输出
    timezone-aware display

预期结果

时间戳 converted 到 desired 格式化, 具有 timezone handling 正确.

常见错误

Confusing seconds and milliseconds
Unix timestamps can be in seconds (10 digits) or milliseconds (13 digits). Check the magnitude and convert accordingly. JavaScript uses milliseconds.
Timezone offset applied incorrectly
Always work in UTC internally and convert to local time only for display. Use explicit timezone libraries for reliable conversion.

排障指引

  • If the date is off by hours, check for a timezone mismatch between the source and your system.
  • If the year is 1970, the timestamp was treated as 0 or parsed incorrectly.

安全限制

  • Timestamp conversion is a pure calculation with no security implications.

相关工具

参考链接