我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
/**
* 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()
}
其他回答
jQuery提供了自己的方法来获取时间戳:
var timestamp = $.now();
(此外,它还实现了(newDate).getTime()表达式)
裁判:http://api.jquery.com/jQuery.now/
Date.getTime()方法可以稍微调整一下:
getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。
将结果除以1000得到Unix时间戳,必要时为floor:
(new Date).getTime() / 1000
Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。
在JavaScript中获取时间戳
在JavaScript中,时间戳是自1970年1月1日以来经过的毫秒数。如果您不打算支持<IE8,可以使用
new Date().getTime(); + new Date(); and Date.now();
直接获取时间戳,而无需创建新的Date对象。
返回所需的时间戳
new Date("11/01/2018").getTime()
我强烈建议使用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的其他方式,请参阅他们的文档
代码Math.floor(newDate().getTime()/1000)可以缩短为newDate/1E3|0。
考虑跳过直接getTime()调用,并使用|0替换Math.floor()函数。最好记住1E3是1000的缩写(大写E比小写表示1E3为常量)。
因此,您将获得以下结果:
var ts=新日期/1E3 |0;console.log(ts);