← 中文资源

简体中文版本

Date.UTC 构造无时区漂移时间戳

用 Date.UTC 按 UTC 字段构造时间戳,月份运算与比较不受本机时区影响。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

epoch ms: 1794907800000
iso: 2026-11-17T09:30:00.000Z
parsed equal: true
utc month: 10 | local month: 10
utc hours: 9
utc hours after shifts: 9,10,8
ms until december: 1175400000

实现说明

演示用的数据放在这几个模块级绑定中:stamp、local、offsets、nextMonth。

使用要点

  • 跑完文件,输出里会留下标记——epoch ms:、iso:、parsed equal:。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件的状态由几个模块级绑定持有:stamp、local、offsets。

核心语句

const offsets = [0, 60, -60].map((minutes) => {
  const shifted = new Date(stamp + minutes * 60_000);
  return shifted.getUTCHours();
});

代码示例

// Date.UTC:按 UTC 字段构造时间戳,不受本机时区影响
const stamp = Date.UTC(2026, 10, 17, 9, 30);
const local = new Date(stamp);
console.log('epoch ms:', stamp);
console.log('iso:', local.toISOString());
console.log('parsed equal:', Date.parse('2026-11-17T09:30:00Z') === stamp);

// 月份从 0 开始;UTC 与本地字段可能不同
console.log('utc month:', local.getUTCMonth(), '| local month:', local.getMonth());
console.log('utc hours:', local.getUTCHours());

// 用固定偏移做比较,避免夏令时影响
const offsets = [0, 60, -60].map((minutes) => {
  const shifted = new Date(stamp + minutes * 60_000);
  return shifted.getUTCHours();
});
console.log('utc hours after shifts:', offsets.join(','));

// 日期运算跨越月份边界时仍然精确
const nextMonth = Date.UTC(2026, 11, 1) - stamp;
console.log('ms until december:', nextMonth);