2016-08-04 32 views
0

在PHP microtime()中返回「microsec sec」中的字符串。在javascript或angularjs中使用PHP microtime()

php microtime() 

如: '0.48445100 1470284726'

在JavaScript中存在的microtime()沒有默認功能。
這麼分的返回類型,其中sec是使用date.getTime()返回秒值UNIX時間戳,如:

var date = new Date(); 
var timestamp = Math.round(date.getTime()/1000 | 0); 

那麼如何讓JavaScript中的「微秒」的價值。

+2

的可能的複製微秒決議[確實的JavaScript提供高分辨率定時器?](http://stackoverflow.com/questions/6875625/does-javascript-provide-a-high-resolution - 時間) –

+0

從日期中減去舍入日期? – zerkms

+0

你真的想用這個做什麼? JS給你毫秒分辨率時間戳。這不是微秒的分辨率,所以以某種方式劃分它並不會讓你感到滿意。什麼是用例? – deceze

回答

6

在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 
} 

編輯: 使用較新的高分辨率時間API這是寶ssible獲得在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; 
} 
+0

thanq Flygenring – Harish98

+0

如果你使用這個來獲得一個看似隨機數,正如問題的評論中所提到的那樣,建議不要使用產生微秒的方法,因爲它似乎沒有太好的工作。然而! – Flygenring