我想要一个表示当前日期和时间的数字,比如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>

其他回答

对于微秒分辨率的时间戳,有性能。现在:

function time() { 
  return performance.now() + performance.timing.navigationStart;
}

例如,这可能产生1436140826653.139,而Date.now仅产生143614086653。

Date.getTime()方法可以稍微调整一下:

getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。

将结果除以1000得到Unix时间戳,必要时为floor:

(new Date).getTime() / 1000

Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。

您只能使用

var timestamp=new Date().getTime();console.log(时间戳);

以获取当前时间戳。不需要做任何额外的事情。

我还没见过

Math.floor(Date.now() / 1000); // current time in seconds

另一个我还没看到的是

var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();

代码Math.floor(newDate().getTime()/1000)可以缩短为newDate/1E3|0。

考虑跳过直接getTime()调用,并使用|0替换Math.floor()函数。最好记住1E3是1000的缩写(大写E比小写表示1E3为常量)。

因此,您将获得以下结果:

var ts=新日期/1E3 |0;console.log(ts);