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


当前回答

/**
 * 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 d = new Date();
console.log(d.valueOf()); 

如果想要一种在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中最简单的方法。

下面是一个生成时间戳的简单函数,格式为: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())));
}

//如果你需要10位数alert('timestamp'+ts());函数ts(){return parseInt(Date.now()/1000);}

表演

今天-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);此代码段仅显示外部基准测试中使用的代码