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


当前回答

更简单的方法:

var timeStamp=event.timestamp || new Date().getTime();

其他回答

下面是一个生成时间戳的简单函数,格式为:mm/dd/yy hh:mi:ss

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())));
}
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);

我强烈建议使用moment.js

moment().valueOf()

要获取自UNIX纪元以来的秒数,请执行

moment().unix()

也可以这样转换时间:

moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()

我一直这么做。没有双关语。

要在浏览器中使用moment.js:

<script src="moment.js"></script>
<script>
    moment().valueOf();
</script>

有关更多详细信息,包括安装和使用MomentJS的其他方式,请参阅他们的文档

对于微秒分辨率的时间戳,有性能。现在:

function time() { 
  return performance.now() + performance.timing.navigationStart;
}

例如,这可能产生1436140826653.139,而Date.now仅产生143614086653。

有很多方法可以做到这一点。

 Date.now() 
 new Date().getTime() 
 new Date().valueOf()

要获取以秒为单位的时间戳,请使用以下方法进行转换:

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