我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
var d = new Date();
console.log(d.valueOf());
其他回答
我喜欢这个,因为它很小:
+new Date
我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:
Date.now()
对于微秒分辨率的时间戳,有性能。现在:
function time() {
return performance.now() + performance.timing.navigationStart;
}
例如,这可能产生1436140826653.139,而Date.now仅产生143614086653。
/**
* Equivalent to PHP's time(), which returns
* current Unix timestamp.
*
* @param {string} unit - Unit of time to return.
* - Use 's' for seconds and 'ms' for milliseconds.
* @return {number}
*/
time(unit = 's') {
return unit == 's' ? Math.floor(Date.now() / 1000) : Date.now()
}
var d = new Date();
console.log(d.valueOf());
var time = Date.now || function() {
return +new Date;
};
time();