JavaScript 中的 Date 对象

在 JavaScript 中,Date 是一个对象,因此必须使用 new 操作符显式创建。

Date 对象包含一个表示自 1970 年 1 月 1 日 UTC 起经过的毫秒数的值。需要注意的是,Date 对象不包含任何时区信息。然而,你可以将其转换为任意时区的字符串。其他方法可以选择日期的某些部分,如月份或星期几,或者你可以将该数字用于计算等操作。

构造函数

默认构造函数会创建一个表示当前时间点的 Date 对象。

const currentMilliSeconds = new Date(); // 创建一个表示当前时间的 Date 对象
alert(currentMilliSeconds);             // 隐式转换为字符串
alert(currentMilliSeconds.toString());  // 显式转换为字符串

alert(currentMilliSeconds.valueOf());   // 获取真实的时间值

你还可以向构造函数传递参数来生成特定的 Date 对象。

// 1000 毫秒 = JavaScript 时间起点后的 1 秒
const pointInTime_1 = new Date(1000);
alert(pointInTime_1);

// 上个世纪最后一分钟的起点
const pointInTime_2 = new Date(1999, 11, 31, 23, 59);
alert(pointInTime_2);

方法

Date 对象的一些常用方法包括:

静态方法
  • Date.now():返回自 1970 年 1 月 1 日 00:00:00 UTC 起经过的毫秒数(根据计算机的时区调整)。
  • Date.UTC():返回自 1970 年 1 月 1 日 00:00:00 UTC 起经过的毫秒数。
  • Date.parse(text):由于浏览器之间的差异和不一致性,强烈不建议使用 Date.parse() 来解析字符串。
实例方法
  • toISOString():以 ISO 8601 格式返回一个字符串。
  • getFullYear():返回完整的 4 位年份。
  • getMonth():返回当前月份 [0 - 11]。
  • getDate():返回当前月份中的日期 [1 - 31]。
  • getDay():返回星期几 [0 - 6]。星期日是 0,其他天按顺序递增。
  • getHours():返回小时数 [0 - 23],基于 24 小时制。
  • getMinutes():返回分钟数 [0 - 59]。
  • getSeconds():返回秒数 [0 - 59]。
  • getTime():返回自 1970 年 1 月 1 日以来的毫秒数。
  • valueOf():返回自 1970 年 1 月 1 日以来的毫秒数,等同于 getTime()
  • getTimezoneOffset():返回 UTC 和本地时间之间的差值(单位:分钟)。
  • setFullYear(year):在 Date 对象中存储完整的 4 位年份。
  • setMonth(month, day):设置月份,并可选择设置日期。0 表示一月,...

Date 转换为整数

Date 可以通过 valueOf() 方法返回一个整数,或者通过在构造函数前加上 + 符号来转换为整数,例如用于“种子”生成伪随机数(PRNG)或进行计算。

const dateAsInteger_1 = new Date().valueOf();
alert(dateAsInteger_1);

const dateAsInteger_2 = +new Date();
alert(dateAsInteger_2);

时区

Date 对象仅包含一个整数(毫秒数)。它并不知道任何时区信息。只要你不在任何形式中指定时区,你的操作默认是在本地时区进行的。

但有时你需要考虑时区。

示例 1

创建一个 UTC 时间:2020 年 1 月 27 日,午夜。

const date_1 = new Date(Date.UTC(2020, 00, 27, 0, 0, 0));
alert(date_1);

// 在不同的时区显示(雅加达时区为 +7)...
const jakartaTime = new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Jakarta', dateStyle: 'full', timeStyle: 'long' }).format(date_1);
alert(jakartaTime);

// ... 原始值没有变化
alert(date_1);
示例 2

假设我们在纽约时区(UTC -5)。

const date_2 = new Date();
console.log(date_2.toString());

// 在另一个时区显示(洛杉矶时区为 UTC -8)
const laTime = new Intl.DateTimeFormat('en-GB', { timeZone: 'America/Los_Angeles', dateStyle: 'full', timeStyle: 'long' }).format(date_2);
console.log(laTime);

// ... 内部值没有变化
console.log(date_2.toString());

新的 API:Temporal

Date 对象存在一些不一致和不足之处,尤其是:时区支持较弱、对非公历的支持不足、缺少日历函数等。可能这些问题会在未来的 JavaScript 版本中通过新的 Temporal API 来修复。

Last modified: Monday, 13 January 2025, 3:02 PM