PHP microtime() in javascript or angularjs


PHP microtime() in javascript or angularjs

在PHP microtime()中,返回"microsec-sec"中的字符串。

php microtime()

例如:"0.48445100 1470284726"

在JavaScript中,microtime()没有默认函数
对返回类型进行如此划分,其中sec在unix时间戳中使用date.getTime()返回sec值,例如:

var date  = new Date();
var timestamp = Math.round(date.getTime()/1000 | 0); 

然后如何在JavaScript中获取"microsc"值。

在PHP中,microtime实际上为您提供了微秒分辨率的几分之一秒。

JavaScript使用毫秒而不是秒作为时间戳,因此您只能获得毫秒分辨率的分数部分。

但要得到这个,你只需要取时间戳,除以1000,得到余数,如下所示:

var microtime = (Date.now() % 1000) / 1000;

为了更完整地实现PHP功能,您可以这样做(从PHP.js缩短):

function microtime(getAsFloat) {
    var s,
        now = (Date.now ? Date.now() : new Date().getTime()) / 1000;
    // Getting microtime as a float is easy
    if(getAsFloat) {
        return now
    }
    // Dirty trick to only get the integer part
    s = now | 0
    return (Math.round((now - s) * 1000) / 1000) + ' ' + s
}

编辑:使用较新的高分辨率时间API可以在大多数现代浏览器中获得微秒级的分辨率

function microtime(getAsFloat) {
    var s, now, multiplier;
    if(typeof performance !== 'undefined' && performance.now) {
        now = (performance.now() + performance.timing.navigationStart) / 1000;
        multiplier = 1e6; // 1,000,000 for microseconds
    }
    else {
        now = (Date.now ? Date.now() : new Date().getTime()) / 1000;
        multiplier = 1e3; // 1,000
    }
    // Getting microtime as a float is easy
    if(getAsFloat) {
        return now;
    }
    // Dirty trick to only get the integer part
    s = now | 0;
    return (Math.round((now - s) * multiplier ) / multiplier ) + ' ' + s;
}