本文實(shí)例講述了PHP實(shí)現(xiàn)獲取毫秒時(shí)間戳的方法。分享給大家供大家參考,具體如下:
PHP獲取毫秒時(shí)間戳,利用microtime()
函數(shù)
php本身沒有提供返回毫秒數(shù)的函數(shù),但提供了一個(gè)microtime()
函數(shù),借助此函數(shù),可以很容易定義一個(gè)返回毫秒數(shù)的函數(shù)。
php的毫秒是沒有默認(rèn)函數(shù)的,但提供了一個(gè)microtime()
函數(shù),該函數(shù)返回包含兩個(gè)元素,一個(gè)是秒數(shù),一個(gè)是小數(shù)表示的毫秒數(shù),借助此函數(shù),可以很容易定義一個(gè)返回毫秒數(shù)的函數(shù),例如:
function getMillisecond() { list($s1, $s2) = explode(' ', microtime()); return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); } /* * 獲取時(shí)間差,毫秒級(jí) */ function get_subtraction() { $t1 = microtime(true); $t2 = microtime(true); return (($t2-$t1)*1000).'ms'; } /* * microsecond 微秒 millisecond 毫秒 *返回時(shí)間戳的毫秒數(shù)部分 */ function get_millisecond() { list($usec, $sec) = explode(" ", microtime()); $msec=round($usec*1000); return $msec; } /* * *返回字符串的毫秒數(shù)時(shí)間戳 */ function get_total_millisecond() { $time = explode (" ", microtime () ); $time = $time [1] . ($time [0] * 1000); $time2 = explode ( ".", $time ); $time = $time2 [0]; return $time; } /* * *返回當(dāng)前 Unix 時(shí)間戳和微秒數(shù)(用秒的小數(shù)表示)浮點(diǎn)數(shù)表示,常用來計(jì)算代碼段執(zhí)行時(shí)間 */ function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } $millisecond = get_millisecond(); $millisecond = str_pad($millisecond,3,'0',STR_PAD_RIGHT); echo date("YmdHis").$millisecond;
運(yùn)行結(jié)果:
20190301013407194
需要注意,在32位系統(tǒng)中php的int最大值遠(yuǎn)遠(yuǎn)小于毫秒數(shù),所以不能使用int類型,而php中沒有l(wèi)ong類型,所以只好使用浮點(diǎn)數(shù)來表示。由于使用了浮點(diǎn)數(shù),如果精度設(shè)置不對(duì),使用echo顯示獲取的結(jié)果時(shí)可能會(huì)不正確,要想看到輸出正確的結(jié)果,精度設(shè)置不能低于13位。
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。