Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 742
Harish98 Avatar asked Aug 04 '16 04:08

Harish98


People also ask

What is Microtime function in PHP?

The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds. The $get_as_float is sent as a parameter to the microtime() function and it returns the string microsec sec by default.

What is microtime?

Definition of microtime : a very short interval of time (as 0.01 millionth of a second) microtime photography.

Is PHP timestamp unique?

Return Value: It returns timestamp based unique identifier as a string. Errors And Exceptions: The uniqid() function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.


1 Answers

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;
}
like image 51
Flygenring Avatar answered Sep 21 '22 10:09

Flygenring