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


当前回答

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

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

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

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

其他回答

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 my_timestamp=~~(Date.now()/1000);

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

对于lodash和下划线用户,请使用_.now。

var timestamp = _.now(); // in milliseconds

JavaScript的工作时间是从纪元开始的毫秒数,而大多数其他语言的工作时间都是秒。您可以使用毫秒来工作,但只要您传递一个值来表示PHP,PHP本机函数可能就会失败。所以,为了确保我总是使用秒,而不是毫秒。

这将为您提供Unix时间戳(以秒为单位):

var unix = Math.round(+new Date()/1000);

这将为您提供自纪元以来的毫秒数(而不是Unix时间戳):

var milliseconds = new Date().getTime();