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