使用 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 中。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。