本文實例講述了PHP實現獲取毫秒時間戳的方法。分享給大家供大家參考,具體如下:
PHP獲取毫秒時間戳,利用microtime()函數
php本身沒有提供返回毫秒數的函數,但提供了一個microtime()函數,借助此函數,可以很容易定義一個返回毫秒數的函數。
php的毫秒是沒有默認函數的,但提供了一個microtime()函數,該函數返回包含兩個元素,一個是秒數,一個是小數表示的毫秒數,借助此函數,可以很容易定義一個返回毫秒數的函數,例如:
- 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 毫秒
- *返回時間戳的毫秒數部分
- */
- function get_millisecond()
- {
- list($usec, $sec) = explode(" ", microtime());
- $msec=round($usec*1000);
- return $msec;
- }
- /*
- *
- *返回字符串的毫秒數時間戳
- */
- function get_total_millisecond()
- {
- $time = explode (" ", microtime () );
- $time = $time [1] . ($time [0] * 1000);
- $time2 = explode ( ".", $time );
- $time = $time2 [0];
- return $time;
- }
- /*
- *
- *返回當前 Unix 時間戳和微秒數(用秒的小數表示)浮點數表示,常用來計算代碼段執行時間
- */
- 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;
運行結果:
20190301013407194
需要注意,在32位系統中php的int最大值遠遠小于毫秒數,所以不能使用int類型,而php中沒有long類型,所以只好使用浮點數來表示。
由于使用了浮點數,如果精度設置不對,使用echo顯示獲取的結果時可能會不正確,要想看到輸出正確的結果,精度設置不能低于13位。
新聞熱點
疑難解答