Har*_*h98 3 javascript php time datetime
在PHP中,microtime()以"microsec sec"返回字符串.
php microtime()
Run Code Online (Sandbox Code Playgroud)
例如:'0.48445100 1470284726'
在JavaScript中没有默认函数microtime().
因此划分返回类型,其中sec在unix时间戳中使用date.getTime()返回的sec值,例如:
var date = new Date();
var timestamp = Math.round(date.getTime()/1000 | 0);
Run Code Online (Sandbox Code Playgroud)
那么如何在JavaScript中获得'microsec'值.
Fly*_*ing 12
在PHP中microtime实际上为您提供微秒分辨率的一秒.
JavaScript使用毫秒而不是秒作为其时间戳,因此您只能获得具有毫秒分辨率的分数部分.
但要得到这个,你只需要取时间戳,除以1000并得到余数,如下所示:
var microtime = (Date.now() % 1000) / 1000;
Run Code Online (Sandbox Code Playgroud)
为了更完整地实现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
}
Run Code Online (Sandbox Code Playgroud)
编辑: 使用较新的高分辨率时间API,可以在大多数现代浏览器中获得微秒分辨率
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8693 次 |
| 最近记录: |