使用 JavaScript 获取 UTC 时间戳

使用 getTime() 方法获取 UTC 时间戳,例如 new Date().getTime()。 该方法返回自 Unix 纪元以来的毫秒数,并始终使用 UTC 表示时间。 从任何时区调用该方法都会返回相同的 UTC 时间戳。

const utcTimestamp = new Date().getTime();

console.log(utcTimestamp);

我们使用 Date.getTime 方法来获取 UTC 时间戳。

该方法返回自 Unix 纪元以来的毫秒数,并始终使用 UTC 表示时间。

如果用户从一个时区访问您的站点,getTime() 方法将返回与任何其他时区相同的结果。

getTime() 方法可用于将日期和时间分配给另一个 Date 对象

const utcTimestamp = new Date().getTime();

console.log(utcTimestamp); // ?️ 16422369....

const copy = new Date();
copy.setTime(utcTimestamp);

console.log(utcTimestamp === copy.getTime()); // ?️ true

如果我们需要日期的 UTC 表示,请使用 toUTCString() 方法。

const utcDate = new Date().toUTCString();

console.log(utcDate); // ?️ Fri, 23 Sep 2022 14:14:29 GMT

toUTCString 方法根据 UTC 将日期转换为字符串。

请注意,GMT 和 UTC 共享相同的当前时间。

它们之间的区别在于 GMT 是一个时区,而 UTC 是一个时间标准,是全球时区的基础。

UTC 和 GMT 不会因夏令时 (DST) 而改变,并且始终共享相同的当前时间。

如果我们需要 UTC 格式的任何日期和时间组件,请使用可用的 getUTC* 方法。

它们非常有用,使我们能够使用字符串连接以多种不同的方式格式化日期和时间。

const date = new Date();

// ?️ returns UTC Hour of the date
console.log(date.getUTCHours()); // ?️ 14

// ?️ returns UTC Minutes of the date
console.log(date.getUTCMinutes()); // ?️ 15

// ?️ returns UTC Seconds of the date
console.log(date.getUTCSeconds()); // ?️ 16

// ?️ returns UTC year of the date
console.log(date.getUTCFullYear()); // ?️ 2022

// ?️ returns UTC month (0-11)
//    0 is January, 11 is December
console.log(date.getUTCMonth()); // ?️ 8

// ?️ returns UTC day of the month (1-31)
console.log(date.getUTCDate()); // ?️ 23

所有 getUTC* 方法都根据通用时间返回日期或时间部分。

注意getUTCMonth 方法将指定日期的月份返回为从零开始的值(0 = 一月,1 = 二月等)

我们可以使用这些值以适合您的用例的方式格式化 UTC 日期。

如果我们需要 getUTC* 方法的完整列表,请访问 MDN 文档

这些方法中的每一个都有一个非 UTC 等效项,例如 getUTCFullYear 与 getFullYear

getUTC* 方法根据通用时间返回日期或时间部分,而 get* 方法根据本地时间(访问者计算机所在的时区)返回它们。

get* 方法会根据用户从何处访问我们的站点返回不同的结果。

例如,如果我们将当地时间午夜 (00:00) 存储在数据库中,我们将不知道这是东京(日本)、巴黎(法国)、纽约(美国)等的午夜。这些都是相隔数小时的不同时刻。

为了保持一致性,当我们必须向用户呈现日期和时间时,我们应该主要使用本地时间,但将实际值存储在 UTC 中。