我想要一个表示当前日期和时间的数字,比如Unix时间戳。


当前回答

我还没见过

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

另一个我还没看到的是

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

其他回答

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

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

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

var timestamp = Number(new Date()); // current time as number
/**
 * 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()
}
var time = Date.now || function() {
  return +new Date;
};

time();

表演

今天-2020.04.23我对选定的解决方案进行测试。我在Chrome 81.0、Safari 13.1和Firefox 75.0上测试了MacOs High Sierra 10.13.6

结论

Solution Date.now()(E)在Chrome和Safari上最快,在Firefox上第二快,这可能是快速跨浏览器解决方案的最佳选择解决方案性能.now()(G),令人惊讶的是,它比Firefox上的其他解决方案快100多倍,但在Chrome上最慢解决方案C、D、F在所有浏览器上都很慢

细节

铬的结果

您可以在此处对机器进行测试

测试中使用的代码显示在下面的代码段中

函数A(){return new Date().getTime();}函数B(){return new Date().valueOf();}函数C(){return+new Date();}函数D(){返回新日期()*1;}函数E(){return Date.now();}函数F(){return Number(new Date());}函数G(){//此解决方案返回从加载页面开始计算的时间。//(在Chrome上,它提供了更好的精度)return performance.now();}//测试log=(n,f)=>console.log(`${n}:${f()}`);日志('A',A);日志('B',B);日志('C',C);日志('D',D);对数('E',E);日志('F',F);日志('G',G);此代码段仅显示外部基准测试中使用的代码