我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
我强烈建议使用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的其他方式,请参阅他们的文档
其他回答
Moment.js可以消除处理Javascript Dates时的许多痛苦。
参见:http://momentjs.com/docs/#/displaying/unix-时间戳/
moment().unix();
更简单的方法:
var timeStamp=event.timestamp || new Date().getTime();
对于微秒分辨率的时间戳,有性能。现在:
function time() {
return performance.now() + performance.timing.navigationStart;
}
例如,这可能产生1436140826653.139,而Date.now仅产生143614086653。
我还没见过
Math.floor(Date.now() / 1000); // current time in seconds
另一个我还没看到的是
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
var timestamp = Number(new Date()); // current time as number