我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
建议的正确方法是Number(new Date()),就代码可读性而言,
此外,UglifyJS和Google闭包编译器将降低已解析代码逻辑树的复杂性(如果您使用其中一个来隐藏/缩小代码)。
对于时间分辨率较低的Unix时间戳,只需将当前数字除以1000,保持整数。
其他回答
console.log(newDate().valueOf());//返回自epoch以来的毫秒数
var time = Date.now || function() {
return +new Date;
};
time();
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())));
}
在JavaScript中获取时间戳
在JavaScript中,时间戳是自1970年1月1日以来经过的毫秒数。如果您不打算支持<IE8,可以使用
new Date().getTime(); + new Date(); and Date.now();
直接获取时间戳,而无需创建新的Date对象。
返回所需的时间戳
new Date("11/01/2018").getTime()
任何不支持Date.now的浏览器,您都可以使用它获取当前日期时间:
currentTime = Date.now() || +new Date()