讲解

JavaScript 的日期时间是 Date 对象。创建:new Date() 取当前时间,new Date(2026, 7, 9) 按「本地时间」构造(注意月份从 0 开始,7 是八月——这是 Date 最著名的坑),new Date('2026-08-09T10:00:00+08:00') 解析 ISO 字符串,new Date(1786329600000) 用毫秒时间戳。读取年月日时分秒用 getFullYear、getMonth(0-11!)、getDate(月中第几天)、getDay(星期几,0 是周日)、getHours 等一组 get 方法;对应的 UTC 版本带 UTC 前缀(getUTCFullYear)。

时间戳是处理日期的「通用语言」:date.getTime() 和 Date.now() 都返回 1970 年以来的毫秒数。比较两个日期先后、计算相差天数,都先转成时间戳做算术,比逐字段比较可靠得多。日期加减没有官方 API,通行做法是转成时间戳加减毫秒(一天 = 86400000 毫秒),或用 setDate(getDate() + 7) 这类自动进位的写法(1 月 32 日自动变 2 月 1 日)。

格式化输出别手写拼接:Intl.DateTimeFormat('zh-CN', { dateStyle: 'long', timeStyle: 'short' }) 按地区习惯格式化,支持时区选项,是国际化的正路。Date 的 API 老旧(可变对象、月份从 0、解析歧义),社区有 Temporal 新标准在逐步落地,学习成本之内建议了解其存在。日常需求(展示、比较、加减)用 Date + Intl 足够。

示例

// 构造:注意月份从 0 开始
const d = new Date(2026, 7, 9, 10, 30, 0); // 2026 年 8 月 9 日 10:30
console.log('年:', d.getFullYear(), '月:', d.getMonth() + 1, '日:', d.getDate());
console.log('星期:', '日一二三四五六'[d.getDay()]);

// 时间戳算术:相差几天
const start = new Date(2026, 0, 1).getTime();
const end = new Date(2026, 7, 9).getTime();
console.log('相差天数:', Math.round((end - start) / 86400000));

// 日期加减:setDate 自动进位
const deadline = new Date(2026, 0, 30);
deadline.setDate(deadline.getDate() + 7);
console.log('7 天后:', deadline.getFullYear() + '-' + (deadline.getMonth() + 1) + '-' + deadline.getDate());

// 比较先后
console.log('先后比较:', new Date(2026, 0, 1) < new Date(2026, 5, 1));

// Intl 格式化
const now = new Date(2026, 7, 9, 15, 30);
console.log(new Intl.DateTimeFormat('zh-CN', { dateStyle: 'full' }).format(now));
console.log(new Intl.DateTimeFormat('zh-CN', { dateStyle: 'short', timeStyle: 'short' }).format(now));
console.log(new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' }).format(now));

// ISO 字符串与时间戳互转
const iso = new Date(0).toISOString();
console.log('ISO:', iso, '解析回时间戳:', Date.parse(iso));

常见坑

  • 月份 0 起点:new Date(2026, 8, 1) 是九月不是八月;getMonth() 返回值要 +1 展示。记法:只有月份从 0 开始,日和年都正常。
  • '2026-08-09' 的解析时区:纯日期字符串按 UTC 解析,东八区 new Date('2026-08-09') 本地日期可能变成 8 月 9 日早上 8 点——用 Date 对象直接展示会差 8 小时。想要本地语义用 new Date(2026, 7, 9)。
  • getDay 与 getDate 混淆:getDay 是星期(0-6),getDate 才是几号。想要几号写了 getDay,展示全乱。
  • Date 对象是可变的:setDate 等方法原地修改对象,把一个 Date 传来传去再各自 set 会互相污染,用前先 new Date(原值) 复制。

小结

Date 记年月日时分秒(月份 0 起点),时间戳算术做比较与加减,Intl.DateTimeFormat 做格式化。下一章学习调试与排错的系统方法。