Unix 时间戳入门:为什么全世界从 1970 年开始数秒Unix Timestamps 101: Why the World Counts Seconds from 1970
时间戳是数据库、日志与 API 的通用语言,但秒/毫秒混用、时区误解造成的 bug 层出不穷。本文讲清时间戳的本质、三个高频事故场景与排查方法。Timestamps are the lingua franca of databases, logs and APIs, yet seconds/milliseconds mix-ups and timezone misunderstandings cause endless bugs. This article explains what timestamps really are and the three most common incident scenarios.
时间戳的本质:一个与地点无关的整数What a timestamp really is: a location-free integer
Unix 时间戳定义为自 1970-01-01 00:00:00 UTC 起经过的秒数。起点(Epoch)源于早期 Unix 系统的历史选择,后来成为全行业惯例。它最大的优点是“与地点无关”:同一时刻,全世界的计算机得到同一个数字,比较、排序、存储都极其简单。A Unix timestamp is the number of seconds elapsed since 1970-01-01 00:00:00 UTC. The epoch is a historical choice from early Unix that became an industry convention. Its greatest virtue is being location-free: at any instant, every computer on Earth computes the same number, making comparison, sorting and storage trivial.
我们平时说的“2026 年 8 月 24 日上午 10 点”则是本地时间——同一时刻在不同时区有不同的本地表达。时间戳与本地时间的互相转换,必须带上时区这个参数,这是理解一切时间问题的钥匙。What we call "10 am on 24 August 2026" is local time — the same instant expressed differently per timezone. Converting between timestamps and local time always requires a timezone parameter; that insight unlocks every time-related problem.
秒与毫秒:相差一千倍的经典事故Seconds vs milliseconds: the 1000x classic
JavaScript 的 Date.now() 返回毫秒(13 位),而 MySQL 的 UNIX_TIMESTAMP() 返回秒(10 位)。前端把毫秒直接传给按秒解析的后端,时间就会飞到 5 万多年后;反之则回到 1970 年附近。这类 bug 在联调期极为常见。JavaScript’s Date.now() returns milliseconds (13 digits) while MySQL’s UNIX_TIMESTAMP() returns seconds (10 digits). Feed milliseconds to a seconds-based backend and dates fly 50,000 years into the future; the reverse lands near 1970. This bug is a rite of passage during integration.
预防方法很简单:团队约定单一单位并在接口文档中写明;跨语言联调时先打印位数核对(10 位秒、13 位毫秒);用时间戳转换工具快速验证可疑数值。Prevention is simple: agree on one unit and document it; when integrating across languages, check the digit count first (10 = seconds, 13 = milliseconds); and use a timestamp converter to sanity-check suspicious values.
时区与夏令时:时间戳没有时区Timezones and DST: timestamps have no timezone
“时间戳差了 8 小时”几乎总是时区问题:服务器按 UTC 记录、客户端按东八区展示,或相反。时间戳本身不含时区信息,差异来自“解释方式”。排查时先统一打印 UTC 时间,再核对各环节的时区配置。"The timestamp is off by 8 hours" is almost always a timezone issue: the server logs in UTC while the client renders in UTC+8, or vice versa. The timestamp itself carries no timezone; the difference comes from interpretation. When debugging, print everything in UTC first, then audit each component’s zone setting.
夏令时则是另一个暗礁:欧美地区一年两次偏移变化,跨夏令时边界计算“1 小时后”不能简单加 3600 秒的本地时间,而应基于时间戳运算后再转回本地。本站的时区转换工具可用来快速核对多地时间。Daylight saving is another reef: in Europe and the Americas the offset shifts twice a year, so "one hour later" across a DST boundary cannot be computed by adding 3600 to local wall-clock time — compute on timestamps, then convert back. Our timezone converter helps verify times across regions quickly.