PHP microtime() in javascript or angularjs
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;
}
Related videos on Youtube
Harish98
Updated on September 14, 2022Comments
-
Harish98 over 1 year
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 usingdate.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.
-
JSchirrmacher over 7 yearsPossible duplicate of Does JavaScript provide a high resolution timer?
-
-
Flygenring over 7 yearsIf you're using this to get a seemingly random number, as asked in the comments to the question, would advice against using the method that produces microseconds, as it doesn't seem to do too good a job at that yet!