Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - 您如何获得JavaScript时间戳?(How do you get a timestamp in JavaScript?)

How can I get a timestamp in JavaScript?

(如何获取JavaScript时间戳?)

Something similar to Unix timestamp , that is, a single number that represents the current time and date.

(与Unix时间戳类似,即代表当前时间和日期的单个数字。)

Either as a number or a string.

(可以是数字或字符串。)

  ask by pupeno translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...