我想要一个表示当前日期和时间的数字,比如Unix时间戳。


当前回答

我还没见过

Math.floor(Date.now() / 1000); // current time in seconds

另一个我还没看到的是

var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();

其他回答

Date.getTime()方法可以稍微调整一下:

getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。

将结果除以1000得到Unix时间戳,必要时为floor:

(new Date).getTime() / 1000

Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。

日期,JavaScript中的原生对象是我们获取所有时间数据的方式。

在JavaScript中要小心,时间戳取决于客户端计算机设置,因此它不是100%准确的时间戳。要获得最佳结果,需要从服务器端获取时间戳。

总之,我更喜欢用香草。这是在JavaScript中实现的常见方法:

Date.now(); //return 1495255666921

在MDN中,如下所述:

Date.now()方法返回自1970年1月1日00:00:00 UTC。因为now()是Date的静态方法,所以您总是将其用作Date.now()。

如果您使用的版本低于ES5,Date.now();不起作用,您需要使用:

new Date().getTime();

更简单的方法:

var timeStamp=event.timestamp || new Date().getTime();
function getTimeStamp() {
    var now = new Date();
    return ((now.getMonth() + 1) + '/' +
            (now.getDate()) + '/' +
             now.getFullYear() + " " +
             now.getHours() + ':' +
             ((now.getMinutes() < 10)
                 ? ("0" + now.getMinutes())
                 : (now.getMinutes())) + ':' +
             ((now.getSeconds() < 10)
                 ? ("0" + now.getSeconds())
                 : (now.getSeconds())));
}
var timestamp = Number(new Date()); // current time as number