使用 JavaScript 获取 GMT 时间戳
JavaScript 中使用 getTime()
方法获取 GMT 时间戳,例如 new Date().getTime()
。 该方法返回自 Unix 纪元以来的毫秒数,并始终使用 UTC 表示时间。 UTC 与 GMT 共享相同的当前时间。
// ✅ get GMT timestamp
const gmtTimestamp = new Date().getTime();
console.log(gmtTimestamp); // 👉️ 1663940749982
// ✅ get GMT date and time
const gmtDateTime = new Date().toUTCString();
console.log(gmtDateTime); // 👉️ Fri, 23 Sep 2022 13:45:49 GMT
我们使用 Date.getTime
方法来获取 GMT 时间戳。
该方法返回自 Unix 纪元以来的毫秒数,并始终使用 UTC 表示时间。
无论访问者的时区如何,该方法都会返回相同的时间戳。
GMT 和 UTC 共享相同的当前时间。
它们之间的区别在于 GMT 是一个时区,而 UTC 是一个时间标准,是全球时区的基础。
UTC
和GMT
不会因夏令时 (DST) 而改变,并且始终共享相同的当前时间。
在第二个示例中,我们使用 toUTCString
方法将日期转换为使用 GMT 时区的字符串。
// ✅ get GMT date and time
const gmtDateTime = new Date().toUTCString();
console.log(gmtDateTime); // 👉️ Fri, 23 Sep 2022 13:45:49 GMT
如果我们需要 GMT 中的任何日期和时间组件,请使用可用的 getUTC*
方法。
它们非常有用,使我们能够使用字符串连接以多种不同的方式格式化日期和时间。
const date = new Date();
// 👇️ returns UTC (=GMT) Hour of the date
console.log(date.getUTCHours()); // 👉️ 7
// 👇️ returns UTC (=GMT) Minutes of the date
console.log(date.getUTCMinutes()); // 👉️ 56
// 👇️ returns UTC (=GMT) Seconds of the date
console.log(date.getUTCSeconds()); // 👉️ 46
// 👇️ returns UTC (=GMT) year of the date
console.log(date.getUTCFullYear()); // 👉️ 2022
// 👇️ returns UTC (=GMT) month (0-11)
// 0 is January, 11 is December
console.log(date.getUTCMonth()); // 👉️ 8
// 👇️ returns UTC (=GMT) day of the month (1-31)
console.log(date.getUTCDate()); // 👉️ 23
所有 getUTC*
方法都根据通用时间 (= GMT)
返回日期或时间部分。
请注意
,getUTCMonth 方法将指定日期的月份返回为从零开始的值(0 = 一月,1 = 二月等)
我们可以使用这些值以适合您用例的方式格式化 GMT 日期。
如果我们需要 getUTC*
方法的完整列表,请访问 MDN 文档。
这些方法中的每一个都有一个非 UTC 等效项,例如 getUTCFullYear
与 getFullYear
。
getUTC*
方法根据通用时间 (= GMT) 返回日期或时间部分,而 get*
方法根据本地时间(访问者计算机所在的时区)返回它们。
get*
方法会根据用户从何处访问您的站点返回不同的结果。
例如,如果我们将当地时间午夜 (00:00) 存储在数据库中,我们将不知道这是东京(日本)、巴黎(法国)、纽约(美国)等的午夜。这些都是相隔数小时的不同时刻。
为了保持一致性,当我们必须向用户呈现日期和时间时,我们应该主要使用本地时间,但将实际值存储在 UTC (=GMT)
中。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。