在PHP microtime()中,返回以"microsec“为单位的字符串。
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中获取“微秒”值。
发布于 2016-08-04 15:26:09
在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
}EDIT :使用新的高分辨率时间应用编程接口,可以在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;
}https://stackoverflow.com/questions/38758655
复制相似问题