我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
我强烈建议使用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);
JavaScript的工作时间是从纪元开始的毫秒数,而大多数其他语言的工作时间都是秒。您可以使用毫秒来工作,但只要您传递一个值来表示PHP,PHP本机函数可能就会失败。所以,为了确保我总是使用秒,而不是毫秒。
这将为您提供Unix时间戳(以秒为单位):
var unix = Math.round(+new Date()/1000);
这将为您提供自纪元以来的毫秒数(而不是Unix时间戳):
var milliseconds = new Date().getTime();
var timestamp = Number(new Date()); // current time as number
var d = new Date();
console.log(d.valueOf());
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())));
}