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

时间:2019-07-02 10:09:42

标签: php datetime

我有一些实例,其中某个任务的日志显示例如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);
}

1 个答案:

答案 0 :(得分:0)

显示毫秒数将取决于您的PHP版本以及您要如何格式化时间:

PHP <7.1:

  1. 格式化MOUSEBUTTONDOWN(秒。微秒)
12:12:12.012342
  1. 设置public function udate() { list($microSecondsPastNow, $nowTimeInSeconds) = explode(" ", microtime()); $microSeconds = $microSecondsPastNow * 1000000; //$microSeconds is now an int, so we need to add leading zeroes to achieve //the desired format. E.g. '000001' when we have 1 microsecond. $formattedMicroSeconds = str_pad($microseconds, 6, '0'); $dateFormat = preg_replace('`(?<!\\\\)u`', $formattedMicroSeconds, 'H:i:s.u') return date($dateFormat, $nowTimeInSeconds); } 的格式(seconds.milliseconds.microseconds)
12:12:12.012.342

PHP> = 7.1:

从7.1版开始,public function udate() { list($microSecondsPastNow, $nowTimeInSeconds) = explode(" ", microtime()); $microSeconds = $microSecondsPastNow * 1000000; //$microSeconds is now an int, so we need to add leading zeroes to achieve //the desired format. E.g. '000001' when we have 1 microsecond. $formattedMicroSeconds = str_pad($microseconds, 6, '0'); $dateFormat = preg_replace('`(?<!\\\\)u`', $formattedMicroSeconds, 'H:i:s.u') list($milliPart, $microPart) = str_split($microSeconds, 3); return date($dateFormat, $nowTimeInSeconds) . ".$milliPart.$microPart"; } 用实际值填充微秒。以前的版本用'0​​00000'填充。因此,如果您最新安装了PHP版本,则大部分工作已经完成。

  1. 格式化new DateTime()(秒。微秒)
12:12:12.012342
  1. 设置public function udate() { $now = new DateTime(); return $now->format('H:i:s.u'); } 的格式(seconds.milliseconds.microseconds)
12:12:12.012.342