如何修复丢失的字符并记录微秒?

    我有一些实例,例如,我的特定任务的日志显示 10:31:06.500(测量到毫秒),而其他时候则显示缺少字符,例如 10:31:06.0。我需要更改什么才能始终显示 3 个字符的毫秒数?另外,我想更进一步,也显示微秒。帮助表示赞赏。


// Log to file

public function logs($msg, $file)

{

    $date = date("d-m-y");

    $time = $this->udate('H:i:s.u');


    $f = fopen("logs/" . $date . "-" . $file . ".txt", 'a');


    fputs($f, trim($time) . ",{$msg}\n");


    fclose($f);

}


// Get millisecond timestamps

public function udate($format, $utimestamp = null)

{

    if (is_null($utimestamp))

        $utimestamp = microtime(true);

    $timestamp = floor($utimestamp);

    $milliseconds = round(($utimestamp - $timestamp) * 1000);

    return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);

}


暮色呼如
浏览 201回答 1
1回答

小唯快跑啊

显示微秒取决于您的 PHP 版本以及您希望如何格式化时间:PHP < 7.1:格式12:12:12.012342(秒.微秒)public function udate(){&nbsp; &nbsp; list($microSecondsPastNow, $nowTimeInSeconds) = explode(" ", microtime());&nbsp; &nbsp; $microSeconds = $microSecondsPastNow * 1000000;&nbsp; &nbsp; //$microSeconds is now an int, so we need to add leading zeroes to achieve&nbsp;&nbsp; &nbsp; //the desired format. E.g. '000001' when we have 1 microsecond.&nbsp; &nbsp; $formattedMicroSeconds = str_pad($microseconds, 6, '0');&nbsp; &nbsp; $dateFormat = preg_replace('`(?<!\\\\)u`', $formattedMicroSeconds, 'H:i:s.u')&nbsp; &nbsp; return date($dateFormat, $nowTimeInSeconds);}格式12:12:12.012.342(秒.毫秒.微秒)public function udate(){&nbsp; &nbsp; list($microSecondsPastNow, $nowTimeInSeconds) = explode(" ", microtime());&nbsp; &nbsp; $microSeconds = $microSecondsPastNow * 1000000;&nbsp; &nbsp; //$microSeconds is now an int, so we need to add leading zeroes to achieve&nbsp;&nbsp; &nbsp; //the desired format. E.g. '000001' when we have 1 microsecond.&nbsp; &nbsp; $formattedMicroSeconds = str_pad($microseconds, 6, '0');&nbsp; &nbsp; $dateFormat = preg_replace('`(?<!\\\\)u`', $formattedMicroSeconds, 'H:i:s.u')&nbsp; &nbsp; list($milliPart, $microPart) = str_split($microSeconds, 3);&nbsp; &nbsp; return date($dateFormat, $nowTimeInSeconds) . ".$milliPart.$microPart";}PHP >= 7.1:从 7.1 版开始,new DateTime()用实际值填充微秒。以前的版本用“000000”填充。因此,如果您使用的是最新的 PHP 版本,则大部分工作已经完成。格式12:12:12.012342(秒.微秒)public function udate(){&nbsp; &nbsp; $now = new DateTime();&nbsp; &nbsp; return $now->format('H:i:s.u');}格式12:12:12.012.342(秒.毫秒.微秒)public function udate(){&nbsp; &nbsp; $now = new DateTime();&nbsp; &nbsp; $microseconds = $now->format('u');&nbsp; &nbsp; list($milliPart, $microPart) = str_split($microseconds, 3);&nbsp; &nbsp; return $now->format('H:i:s') . ".$milliPart.$microPart";}
打开App,查看更多内容
随时随地看视频慕课网APP