Harish Kesari Harish Kesari - 3 months ago 33
Javascript Question

PHP microtime() in javascript or angularjs

In PHP microtime() return the string in "microsec sec".

php microtime()


eg: '0.48445100 1470284726'

In JavaScript there is no default function for
microtime()
.

So divided the return type, where sec is in unix timestamp using
date.getTime()
returned the sec value, eg:

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


Then how to get the 'microsec' value in JavaScript.

Answer

In PHP microtime actually gives you the fraction of a second with microsecond resolution.

JavaScript uses milliseconds and not seconds for its timestamps, so you can only get the fraction part with millisecond resolution.

But to get this, you would just take the timestamp, divide it by 1000 and get the remainder, like this:

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

For a more complete implementation of the PHP functionality, you can do something like this (shortened from 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
}

EDIT : Using the newer High Resolution Time API it's possible to get microsecond resolutions in most modern browsers

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;
}
Comments