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


当前回答

time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);

其他回答

有时我需要在xmlhttp调用的对象中使用它,所以我喜欢这样做。

timestamp : parseInt(new Date().getTime()/1000, 10)
var d = new Date();
console.log(d.valueOf()); 
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())));
}

我喜欢这个,因为它很小:

+new Date

我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:

Date.now()

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

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

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

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