你如何在 JavaScript 中获得时间戳? [英] How do you get a timestamp in JavaScript?

查看:35
本文介绍了你如何在 JavaScript 中获得时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于 Unix 的时间戳,它是代表当前时间和日期的单个数字.可以是数字或字符串.

解决方案

Short &时髦:

+ new Date()

plus 这样的一元运算符会触发 Date 对象中的 valueOf 方法,并返回时间戳(没有任何更改).

详情:

在几乎所有当前浏览器上,您都可以使用 Date.now()毫秒为单位获取UTC时间戳;一个值得注意的例外是 IE8 及更早版本(参见 兼容性表).

不过,您可以轻松地为此制作一个垫片:

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

要以为单位获取时间戳,您可以使用:

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

或者你可以使用:

Date.now()/1000 |0

应该稍微快一点,但可读性也较差.
(也看到这个答案this 以及对按位运算符的进一步解释).

我建议使用 Date.now()(带有兼容性垫片).它稍微好一点,因为它更短&不会创建新的 Date 对象.但是,如果你不想要一个垫片 &最大的兼容性,你可以使用旧的"以毫秒为单位获取时间戳的方法:

new Date().getTime()

然后您可以像这样将其转换为秒:

Math.round(new Date().getTime()/1000)

你也可以使用我们上面展示的 valueOf 方法:

new Date().valueOf()

时间戳(以毫秒为单位)

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

Something similar to Unix's timestamp, that is a single number that represents the current time and date. Either as a number or a string.

解决方案

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).

Details:

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 or this with further explaination to bitwise operators).

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 like this:

Math.round(new Date().getTime()/1000)

And you can also use the valueOf method which we showed above:

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

这篇关于你如何在 JavaScript 中获得时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆