PHP擷取毫秒時間戳記

來源:互聯網
上載者:User
我們知道,PHP中time()函數擷取的時間戳記,其單位是秒.

但是,前端JS擷取的時間戳記,單位是毫秒.

那麼,在實際應用中,如何將JS和PHP的時間戳記統一,即如何使用PHP擷取毫秒時間戳記呢,請看下例:

php

//函數,擷取毫秒時間戳記

function getMillisecond() {

list($t1, $t2) = explode(' ', microtime());

return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);

}

//上面的函數是百度出來的,我剛開始看著也不是很明白.

//現分開詳細講解如下:

function getMillisecond_new(){

//使用microtime()擷取微秒時間戳記,格式(中間空格隔開):'秒的小數部分 秒的整數部分',例如'0.69718900 1420440552'

//將微秒字串explode炸開,接收$t1=0.69718900 $t2=1420440552

list($t1, $t2) = explode(' ', microtime());

//轉成浮點數

$t1=floatval($t1);

$t2=floatval($t2);

//相加×1000

$total=( $t1+ $t2) * 1000;

//四捨五入

$total=round($total,0);

//返回結果

return $total;

}

echo getMillisecond()," PHP毫秒-getMillisecond()
";

echo getMillisecond_new().' PHP毫秒-getMillisecond_new()';

/*

* 思路:

* 1.使用microtime()擷取微秒時間戳記,格式:0.69718900 1420440552

* 2.前後兩部分相加×1000,然後四捨五入round($float,0)

* 秒time()-->毫秒-->微秒microtime(),兩兩之間是1000進位

* 這樣,就可以與前端JS的時間戳記保持一致

* JS : new Date().getTime()獲得毫秒時間戳記

*/

?>

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

>

>

-equiv="Content-Type" content="text/html; charset=utf-8">

time</title>

head>

>


/
>

>

var time=new Date();

var mtime=time.getTime();

document.write(mtime+' JS獲得毫秒時間戳記');

script>

body>

html>

運行結果如下:

1424069168633 PHP毫秒-getMillisecond()

1424069168633 PHP毫秒-getMillisecond_new()

1424069168643 JS獲得毫秒時間戳記

可以看出,第三個時間戳記數值稍微比前兩個大,這是代碼運行所消耗的時間,是正常的.

以上就介紹了PHP擷取毫秒時間戳記,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.