我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
Date.getTime()方法可以稍微调整一下:
getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。
将结果除以1000得到Unix时间戳,必要时为floor:
(new Date).getTime() / 1000
Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。
其他回答
如果用于日志记录,则可以使用ISOString
new Date().toISOString()
“2019-05-18T20:02:36.694Z”
代码Math.floor(newDate().getTime()/1000)可以缩短为newDate/1E3|0。
考虑跳过直接getTime()调用,并使用|0替换Math.floor()函数。最好记住1E3是1000的缩写(大写E比小写表示1E3为常量)。
因此,您将获得以下结果:
var ts=新日期/1E3 |0;console.log(ts);
下面是一个生成时间戳的简单函数,格式为: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())));
}
我喜欢这个,因为它很小:
+new Date
我也喜欢这个,因为它同样短,而且与现代浏览器兼容,超过500人投票认为它更好:
Date.now()
如果想要一种在Node.js中生成时间戳的基本方法,这很好。
var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
我们的团队正在使用此方法在本地主机环境中破坏缓存。输出是/dist/css/global.css?v=245521377,其中245521377是hrtime()生成的时间戳。
希望这会有所帮助,上面的方法也可以工作,但我发现这是Node.js中最简单的方法。