在JavaScript中,如何获取时间戳?

发布时间 2023-10-13 19:36:51作者: 小满独家

内容来自 DOC https://q.houxu6.top/?s=在JavaScript中,如何获取时间戳?

我想要一个单独的数字,代表当前的日期和时间,就像Unix时间戳一样。


毫秒级时间戳

要获取自Unix纪元以来的毫秒数,调用Date.now:

Date.now()

或者使用一元运算符 + 来调用 Date.prototype.valueOf:

+ new Date()

或者直接调用 valueOf:

new Date().valueOf()

为了支持IE8及更早版本(参见兼容性表(http://kangax.github.io/compat-table/es5/#Date.now)),可以创建一个 shim 用于 Date.now:

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

或者直接调用 getTime:

new Date().getTime()

秒级时间戳

要获取自Unix纪元以来的秒数,即Unix时间戳

Math.floor(Date.now() / 1000)

或者使用按位或运算符来向下取整,略微更快,但可读性较差,并且可能会在未来出现问题(参见说明1, 2):

Date.now() / 1000 | 0

更高精度的毫秒级时间戳

使用performance.now:

var isPerformanceSupported = (
    window.performance &&
    window.performance.now &&
    window.performance.timing &&
    window.performance.timing.navigationStart
);

var timeStampInMs = (
    isPerformanceSupported ?
    window.performance.now() +
    window.performance.timing.navigationStart :
    Date.now()
);

console.log(timeStampInMs, Date.now());