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


当前回答

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

其他回答

代码Math.floor(newDate().getTime()/1000)可以缩短为newDate/1E3|0。

考虑跳过直接getTime()调用,并使用|0替换Math.floor()函数。最好记住1E3是1000的缩写(大写E比小写表示1E3为常量)。

因此,您将获得以下结果:

var ts=新日期/1E3 |0;console.log(ts);

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

+new Date

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

Date.now()

Moment.js可以消除处理Javascript Dates时的许多痛苦。

参见:http://momentjs.com/docs/#/displaying/unix-时间戳/

moment().unix();

jQuery提供了自己的方法来获取时间戳:

var timestamp = $.now();

(此外,它还实现了(newDate).getTime()表达式)

裁判:http://api.jquery.com/jQuery.now/

//如果你需要10位数alert('timestamp'+ts());函数ts(){return parseInt(Date.now()/1000);}