1. 程式人生 > >PHP輸出時間精確到毫秒

PHP輸出時間精確到毫秒

<?php
/**
 * Created by PhpStorm.
 * User: jefferyteng
 * Date: 2018/8/28
 * Time: 10:00
 */

/*1、直接列印微秒0.24754300 1535423356*/
echo(microtime());
echo "<br/>";

/*2、十三位時間戳,包含毫秒1535423356248*/
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}
echo msectime();
echo "<br/>";


//3、獲取當前系統時間並列印
$date = new DateTime();
echo $date->format('Y-m-d H:i:s');
echo "<br/>";




/*4、完整的時間:2018-08-28 10:29:16 247591*/
function udate($format = 'u', $utimestamp = null)
{
    if (is_null($utimestamp)){
        $utimestamp = microtime(true);
    }
    $timestamp = floor($utimestamp);
    $milliseconds = round(($utimestamp - $timestamp) * 1000000);//改這裡的數值控制毫秒位數
    return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}
echo udate('Y-m-d H:i:s u');
echo "<br/>";


//5、只要毫秒+微秒:247624
function milliseconds($format = 'u', $utimestamp = null)
{
    if (is_null($utimestamp)){
        $utimestamp = microtime(true);
    }
    $timestamp = floor($utimestamp);
    $milliseconds = round(($utimestamp - $timestamp) * 1000000);//改這裡的數值控制毫秒位數
    return $milliseconds;
}
echo milliseconds();