2016年1月17日 星期日

How do you get a timestamp in JavaScript?

On almost all current browsers you can use Date.now() to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).
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). It's slightly better because it's shorter & doesn't create a new Date object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:
new Date().getTime()
Which you can then convert to seconds using the same method as above.

reference : http://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript

沒有留言:

wibiya widget