我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
Moment.js可以消除处理Javascript Dates时的许多痛苦。
参见:http://momentjs.com/docs/#/displaying/unix-时间戳/
moment().unix();
其他回答
您只能使用
var timestamp=new Date().getTime();console.log(时间戳);
以获取当前时间戳。不需要做任何额外的事情。
下面是一个生成时间戳的简单函数,格式为: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())));
}
console.log(newDate().valueOf());//返回自epoch以来的毫秒数
var time = Date.now || function() {
return +new Date;
};
time();
我喜欢这个,因为它很小:
+new Date
我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:
Date.now()