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.
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.
Definition of microtime : a very short interval of time (as 0.01 millionth of a second) microtime photography.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With