我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
//当前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>
其他回答
//如果你需要10位数alert('timestamp'+ts());函数ts(){return parseInt(Date.now()/1000);}
我强烈建议使用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的其他方式,请参阅他们的文档
这似乎奏效了。
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
在写这篇文章时,最重要的答案是9年前的事了,从那以后发生了很多变化——最重要的是,我们几乎得到了对非黑客解决方案的普遍支持:
Date.now()
如果你想绝对肯定这不会在某些古老的(ie9之前的)浏览器中出现,你可以将其置于检查之后,如下所示:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
当然,这将返回自纪元时间以来的毫秒,而不是秒。
Date.now上的MDN文档
时间戳(毫秒)
要获取自Unix纪元以来的毫秒数,请调用Date.now:
Date.now()
或者,使用一元运算符+调用Date.prototype.valueOf:
+ new Date()
或者,直接调用valueOf:
new Date().valueOf()
要支持IE8和更早版本(请参阅兼容性表),请为Date.now创建一个垫片:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
或者,直接调用getTime:
new Date().getTime()
时间戳(秒)
要获取自Unix纪元以来的秒数,即Unix时间戳:
Math.floor(Date.now() / 1000)
或者,使用逐位或逐层稍快,但可读性也较低,将来可能会中断(参见解释1、2):
Date.now() / 1000 | 0
以毫秒为单位的时间戳(分辨率更高)
使用performance.now:
var isPerformanceSupported=(窗口.性能&&窗口.性能.当前&&窗口.性能.计时&&窗口.性能.计时.导航开始);var timeStampInMs=(是否支持性能?window.performance.now()+窗口.性能.计时.导航开始:日期.now());console.log(timeStampInMs,Date.now());