我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
我喜欢这个,因为它很小:
+new Date
我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:
Date.now()
其他回答
任何不支持Date.now的浏览器,您都可以使用它获取当前日期时间:
currentTime = Date.now() || +new Date()
Date.getTime()方法可以稍微调整一下:
getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。
将结果除以1000得到Unix时间戳,必要时为floor:
(new Date).getTime() / 1000
Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。
/**
* 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()
}
代码Math.floor(newDate().getTime()/1000)可以缩短为newDate/1E3|0。
考虑跳过直接getTime()调用,并使用|0替换Math.floor()函数。最好记住1E3是1000的缩写(大写E比小写表示1E3为常量)。
因此,您将获得以下结果:
var ts=新日期/1E3 |0;console.log(ts);
//当前Unix时间戳//自1970年1月1日起,1443534720秒。(UTC)//秒console.log(数学地板(newDate().valueOf()/1000));//1443534720console.log(数学地板(Date.now()/1000));//1443534720console.log(数学地板(newDate().getTime()/1000));//1443534720//毫秒console.log(数学地板(newDate().valueOf()));//1443534720087console.log(数学地板(Date.now()));//1443534720087console.log(数学地板(newDate().getTime()));//1443534720087//jQuery//秒console.log(数学地板($.now()/1000));//1443534720//毫秒console.log($.now());//1443534720087<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script>