← 全部文章

毫秒 vs 秒:如何把 millis 转换为 Unix timestamp

最常见的时间戳 bug 是在期望秒的地方传入毫秒,或反过来。学习 10 位与 13 位法则、各语言默认值、对数据库的影响,以及安全的转换模式。

为什么有两个标准

Unix 时间最初以秒定义——对一个每个时钟滴答递增一次的系统来说,整数很自然。JavaScript 的 Date 对象于 1995 年引入,选择毫秒以支持浏览器中亚秒级的事件计时。许多数据库和后端语言保留 Unix 秒为默认。如今两种标准在每段跨越 JavaScript 与服务器边界的代码中并存,这就是为什么一个值可能看起来有效却表示数万年之后的日期。

每种语言使用的单位

记住这种分裂最稳妥的方法是:浏览器 Date API 通常要毫秒,Unix 风格的服务器 API 通常暴露秒,而较新的时间库往往两者都提供。阅读第三方 API 文档时,不要仅凭语言推断单位;查看字段说明和示例。

  • Milliseconds: JavaScript Date.now(), Java System.currentTimeMillis(), Java Instant.toEpochMilli(), .NET ToUnixTimeMilliseconds()
  • Seconds: Python time.time() (float), PHP time(), Go time.Now().Unix(), Ruby Time.now.to_i, C time(NULL), PostgreSQL EXTRACT(EPOCH)
  • Both: Rust — duration.as_secs() for seconds, duration.as_millis() for milliseconds
  • Python note: time.time() returns a float, so milliseconds are available as int(time.time() * 1000)

从值自动识别单位

对现代日期可靠的经验法则:10 位数字是秒,13 位数字是毫秒。当前 Unix 秒约为 17–21 亿(10 位),直到公元 33658 年才会达到 13 位。当前 Unix 毫秒已是 13 位。该法则在从 2000 年代到未来数千年间最为可靠;对历史日期、负日期或紧凑的测试夹具,请使用显式单位而非猜测。

  • 10 位的值 → 秒(如 1700000000 = 2023-11-14 UTC)
  • 13 位的值 → 毫秒(如 1700000000000 = 2023-11-14 UTC)
  • 16 位的值 → 微秒(除以 1,000,000 得到秒)
  • 负值 → 1970 年 1 月 1 日之前的日期(秒或毫秒)

安全的转换模式

转换本身是简单的算术;难点在于选择在哪里进行转换。在系统边界处转换,为转换后的值命名,避免把含糊的原始数字穿过多层传递。

  • Seconds to milliseconds: seconds * 1000
  • Milliseconds to whole seconds — JavaScript: Math.floor(ms / 1000)
  • Milliseconds to whole seconds — Python: ms // 1000
  • Milliseconds to whole seconds — Go: ms / 1000 (integer division)
  • Universal guard in JavaScript: const toMs = ts => ts < 1e11 ? ts * 1000 : ts

单位 bug 在生产中如何显现

秒对毫秒的 bug 常能通过校验,因为两个值都只是数字。它通常稍后表现为不可能的日期:把秒当作毫秒时 JavaScript 显示 1970 年 1 月,后端把毫秒当作秒时显示遥远的未来年份。

  • JavaScript UI 中出现 1970 年日期 → 把秒传给 new Date() 而未乘以 1000
  • Python、Go 或 PHP 中出现 50000 年以上 → 把毫秒传给了期望秒的 API
  • 永不过期的过期令牌 → 过期时间戳以错误单位存储
  • 立即消失的缓存项 → 毫秒被除了两次或秒被乘了两次
  • 范围为空的分析图表 → 查询边界使用了与已存事件时间戳不同的单位

API 与数据库的命名约定

一个很小的命名约定就能避免大多数此类 bug。除非文档异常清晰,否则永远不要发布名为 timestamp 的 API 字段。优先使用同时包含含义和单位的字段名。

  • createdAtMs — Unix milliseconds, best for JavaScript clients
  • createdAtSeconds — Unix seconds, common for backend services
  • createdAtIso — ISO 8601 string, useful for human-readable API responses
  • expiresAtUnixSeconds — explicit enough for auth tokens and signed URLs
  • event_time TIMESTAMPTZ — native database time, with conversion handled by the database

毫秒 vs 秒常见问题

A tiny naming convention prevents most of these bugs. Never publish an API field called timestamp unless the documentation is unusually clear. Prefer field names that include both meaning and unit.

  • createdAtMs — Unix milliseconds, best for JavaScript clients
  • createdAtSeconds — Unix seconds, common for backend services
  • createdAtIso — ISO 8601 string, useful for human-readable API responses
  • expiresAtUnixSeconds — explicit enough for auth tokens and signed URLs
  • event_time TIMESTAMPTZ — native database time, with conversion handled by the database

Microseconds (16 digits) and nanoseconds (19 digits)

Most production timestamps are seconds (10 digits) or milliseconds (13 digits), but two higher-precision formats also appear in real systems — microseconds and nanoseconds. The same digit-counting rule extends.

  • 10 digits ≈ Unix seconds (~1.7×10⁹ today)
  • 13 digits ≈ Unix milliseconds (~1.7×10¹²)
  • 16 digits ≈ Unix microseconds (~1.7×10¹⁵) — Python time.time_ns()/1000, Postgres TIMESTAMP precision 6
  • 19 digits ≈ Unix nanoseconds (~1.7×10¹⁸) — Java Instant.toEpochNano(), Go time.UnixNano(), Temporal.Instant.epochNanoseconds
  • PostgreSQL to_timestamp() takes seconds with an optional fractional part; passing milliseconds yields a date around the year 55000
  • Convert from any precision to milliseconds via integer arithmetic before doing further math
  • Silent truncation: if a database column has millisecond precision but you store nanoseconds, the bottom 6 digits are dropped on insert

How many microseconds in a second? 1 second to milliseconds, microseconds to milliseconds

A quick reference for the unit math that drives every seconds/milliseconds/microseconds bug. The questions "how many microseconds in a second", "1 second to milliseconds", and "microseconds to milliseconds" are all powers of 1000 — but every order of magnitude is one place where production code goes wrong. Keep the table below within reach when writing high-resolution timestamp code.

  • 1 second to milliseconds = 1,000 ms (10³)
  • How many microseconds in a second? = 1,000,000 µs (10⁶)
  • 1 second to nanoseconds = 1,000,000,000 ns (10⁹)
  • Microseconds to milliseconds = µs ÷ 1,000 (10³ step down)
  • Milliseconds to microseconds = ms × 1,000
  • Nanoseconds to microseconds = ns ÷ 1,000
  • Common precision: JavaScript Date.now() = ms, performance.now() = sub-ms float, Go time.UnixNano() = ns, Postgres TIMESTAMP precision 6 = µs
  • Bug pattern: an API returns µs, code divides by 1000 once expecting seconds — actually got ms; result is 1000× off

Millisecond timer, time to ms, milliseconds to seconds conversion

Quick reference for the unit phrasings: "time to ms" (any time value scaled into milliseconds), "milliseconds to seconds conversion" (÷1000), and "millisecond timer" (a high-resolution timer for short intervals). For measuring elapsed time prefer a monotonic clock — wall-clock time can jump backwards on NTP correction or DST.

  • Time to ms / time to milliseconds: seconds × 1000 = ms; microseconds ÷ 1000 = ms; nanoseconds ÷ 1,000,000 = ms
  • Milliseconds to seconds conversion: ms ÷ 1000 = seconds; Math.floor(ms/1000) for integer seconds
  • Millisecond timer (JavaScript): performance.now() returns sub-ms float since page load; Date.now() returns wall-clock ms
  • Millisecond timer (Python): time.perf_counter() (monotonic float seconds); time.monotonic_ns() returns ns
  • Millisecond timer (Java): System.nanoTime() for monotonic ns; Instant.now() for wall-clock ns precision
  • Stopwatch rule: use monotonic clocks for elapsed time; wall-clock can jump backwards on NTP or DST

FAQ

Is a 13-digit timestamp always milliseconds?
For modern real-world Unix timestamps, yes: 13 digits usually means milliseconds. Very far-future seconds timestamps can also reach 13 digits, so critical systems should still carry explicit unit metadata.
Should I store seconds or milliseconds?
Store the unit your system naturally uses, but document it and keep it consistent. JavaScript-heavy systems often use milliseconds; Unix-style backends and many databases commonly use seconds or native datetime columns.
Why use Math.floor(ms / 1000) instead of ms / 1000?
Unix seconds are usually whole seconds. Math.floor removes the fractional part so APIs expecting integer seconds do not receive a decimal value.
How do I convert milliseconds to seconds?
Divide by 1000 and drop the fraction: Math.floor(ms / 1000) in JavaScript, ms // 1000 in Python, or ms / 1000 with integer division in Go. To go the other way, multiply seconds by 1000.