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

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

问题描述

如何在JavaScript中获取时间戳?

How can I get a timestamp in JavaScript?

与Unix的时间戳类似,也就是代表当前时间和日期的单个数字。作为一个数字或一个字符串。

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

像$ 的一元运算符触发 valueOf 方法 Date 对象,它返回时间戳(没有任何更改)。

A unary operator like plus triggers the valueOf method in the Date object and it returns the time-stamp (without any alteration).

详细信息: / strong>

Details:

几乎所有当前的浏览器都可以使用 Date.now() 以在毫秒中获取UTC时间戳;一个显着的例外是IE8及更早版本(请参阅兼容性表

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)

或者您可以使用:

Date.now() / 1000 | 0

哪些应该稍微更快一点,但也更少可读(也看到这个答案)。

Which should be slightly faster, but also less readable (also see this answer).

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

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)

您还可以使用我们上面显示的 valueOf 方法:

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

new Date().valueOf()

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

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