Date 方法

1. 实例化日期的四种方式

// 1. 当前时间
const d1 = new Date();

// 2. 距 1970-01-01 的毫秒数
const d2 = new Date(1700000000000);

// 3. 日期字符串(推荐 ISO 8601)
const d3 = new Date('2024-01-15T08:00:00');

// 4. 年月日时分秒(注意:月份是 0-11)
const d4 = new Date(2024, 0, 15, 8, 0, 0, 0);

2. 常用 Date 对象方法

获取类(本地时区):

  • getFullYear() —— 4 位年份。
  • getMonth() —— 月份(0-11,使用时需 +1)。
  • getDate() —— 当月第几天(1-31)。
  • getDay() —— 星期几(0-6,0 为周日)。
  • getHours() / getMinutes() / getSeconds() / getMilliseconds() —— 时/分/秒/毫秒。

UTC 版本(带 UTC 前缀):

  • getUTCFullYear()、getUTCMonth()、getUTCDate()、getUTCDay()、getUTCHours() 等。

设置类:

  • setFullYear()、setMonth()、setDate()、setHours()、setMinutes()、setSeconds() 等。

格式化与解析:

  • toString() / toDateString() / toTimeString() —— 人类可读字符串。
  • toISOString() —— ISO 8601 字符串(网络传输推荐)。
  • toJSON() —— 同 toISOString(),为 JSON.stringify 自动调用。
  • Date.now() —— 当前时间的毫秒时间戳(静态方法)。
  • Date.parse(str) —— 解析时间字符串为毫秒数(静态方法)。
const d = new Date('2024-01-15T08:00:00');
d.toISOString();        // '2024-01-15T00:00:00.000Z'
Date.now();             // 当前时间戳

补充:处理日期推荐使用成熟的库(如 dayjs、date-fns),原生 Date API 繁琐且易踩时区/夏令时坑;时间戳单位是毫秒,JS 内部使用 UTC,构造时区依赖运行环境。

来源整理自:vue3js.cn 面试官系列