同一个时间戳为什么显示成两天
一条记录可能在 UTC 看起来属于 4 月 10 日,在上海却属于 4 月 11 日。这个差异来自日期的计算口径。时间戳标记同一个瞬间,日历上的日期取决于用哪个时区读它。任务记录、导出文件名和日报这类有“当天”概念的功能,需要先统一这套口径。

从同一个时刻生成两个日期键
示例输入以 Z 结尾,明确表示 UTC。用 Intl.DateTimeFormat 指定时区,通过 formatToParts 拿到年、月、日,再按程序约定组合成日期键。这样也避免了依赖本地化展示字符串里的分隔符和字段顺序。以下代码可保存为 date-key.cjs ,在 Node.js 22 运行 node date-key.cjs 。
const assert = require('node:assert/strict');
function makeDateKeyFormatter(timeZone) {
const formatter = new Intl.DateTimeFormat('en-GB', {
timeZone,
calendar: 'gregory',
numberingSystem: 'latn',
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
return (instant) => {
const parts = Object.fromEntries(formatter.formatToParts(instant)
.map(({ type, value }) => [type, value]));
return [parts.year, parts.month, parts.day].join('-');
};
}
const instant = new Date('2026-04-10T16:30:00Z');
const utcDateKey = makeDateKeyFormatter('UTC');
const shanghaiDateKey = makeDateKeyFormatter('Asia/Shanghai');
assert.equal(utcDateKey(instant), '2026-04-10');
assert.equal(shanghaiDateKey(instant), '2026-04-11');
assert.equal(shanghaiDateKey(new Date('2026-04-10T15:59:59Z')), '2026-04-10');
console.log('UTC', utcDateKey(instant));
console.log('上海', shanghaiDateKey(instant));
把日期口径交给使用记录的一方
如果报表按上海自然日汇总,可以保留原始时间戳,再用指定时区算出分组键。以后按 UTC 导出,同一条记录仍能按新的规则计算。直接用 instant.toISOString().slice(0, 10) 也能得到日期键,但那个结果始终使用 UTC。业务规则明确按 UTC 归档时,这个写法才与口径一致。
需要把日期显示给用户时,可以继续用指定时区的 Intl.DateTimeFormat ,样式按界面语言选择。分组键则保持固定的年月日字段顺序。日期边界是适合写断言的地方,尤其是一个时区仍在当天、另一个已跨到次日的时刻。示例还验证上海午夜前一秒,能用来发现日期被提前归入下一天的问题。

用一个跨午夜的示例说明同一时间戳在 UTC 和上海时区的日期差异,再用 Intl.DateTimeFormat 生成展示日期和按时区归档的日期键。
浙公网安备 33010602011771号