Short & Snazzy:(简短而时髦:)
+ new Date()
A unary operator like plus
triggers the valueOf
method in the Date
object and it returns the timestamp (without any alteration).
(像plus
这样的一元运算符会触发Date
对象中的valueOf
方法,并返回时间戳(不做任何更改)。)
Details:
(细节:)
On almost all current browsers you can use Date.now()
to get the UTC timestamp in milliseconds ;
(在几乎所有当前的浏览器上,您都可以使用Date.now()
来获取UTC时间戳(以毫秒为单位) ;)
a notable exception to this is IE8 and earlier (see compatibility table ).(IE8和更早版本是一个明显的例外(请参阅兼容性表 )。)
You can easily make a shim for this, though:
(不过,您可以轻松地对此进行填充:)
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
To get the timestamp in seconds , you can use:
(要获取以秒为单位的时间戳,可以使用:)
Math.floor(Date.now() / 1000)
Or alternatively you could use:
(或者,您可以使用:)
Date.now() / 1000 | 0
Which should be slightly faster, but also less readable (also see this answer ).
(这应该稍快一些,但可读性也要差一些(另请参见此答案 )。)
I would recommend using Date.now()
(with compatibility shim).
(我建议使用Date.now()
(具有兼容性垫片)。)
It's slightly better because it's shorter & doesn't create a new Date
object.(它稍微好一点,因为它更短并且不会创建新的Date
对象。)
However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds :(但是,如果您不希望使用Shim和最大的兼容性,则可以使用“旧”方法来获取时间戳(以毫秒为单位) :)
new Date().getTime()
Which you can then convert to seconds like this:
(然后您可以将其转换为秒,如下所示:)
Math.round(new Date().getTime()/1000)
And you can also use the valueOf
method which we showed above:
(您还可以使用上面显示的valueOf
方法:)
new Date().valueOf()
Timestamp in Milliseconds
(时间戳(毫秒))
var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now(); console.log(timeStampInMs, Date.now());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…