Skip to content
This repository was archived by the owner on Oct 3, 2023. It is now read-only.

Commit f1bc0dd

Browse files
Bogdan Drutuchingor13
authored andcommitted
Fix bug that can cause the timestamp to be 1 second later. (#161)
* Fix bug that can cause the timestamp to be 1 second later. * Fix typo. * Fix format issues. * Fix build.
1 parent ca25c80 commit f1bc0dd

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/Trace/Span.php

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -342,20 +342,29 @@ private function formatDate($when = null)
342342
{
343343
if (!$when) {
344344
// now
345-
list($usec, $sec) = explode(' ', microtime());
346-
$micro = sprintf("%06d", $usec * 1000000);
347-
$when = new \DateTime(date('Y-m-d H:i:s.' . $micro));
345+
$when = $this->formatFloatTimeToDate(microtime(true));
348346
} elseif (is_numeric($when)) {
349-
// Expect that this is a timestamp
350-
$micro = sprintf("%06d", ($when - floor($when)) * 1000000);
351-
$when = new \DateTime(date('Y-m-d H:i:s.'. $micro, (int) $when));
347+
$when = $this->formatFloatTimeToDate($when);
352348
} elseif (!$when instanceof \DateTimeInterface) {
353349
throw new \InvalidArgumentException('Invalid date format. Must be a \DateTimeInterface or numeric.');
354350
}
355351
$when->setTimezone(new \DateTimeZone('UTC'));
356352
return $when;
357353
}
358354

355+
/**
356+
* Converts a float timestamp into a \DateTimeInterface object.
357+
*
358+
* @param float $when The Unix timestamp to be converted.
359+
* @return \DateTimeInterface
360+
*/
361+
private function formatFloatTimeToDate($when)
362+
{
363+
$sec = floor($when);
364+
$micro = sprintf("%06d", ($when - $sec) * 1000000);
365+
return new \DateTime(date('Y-m-d H:i:s.'. $micro, $sec));
366+
}
367+
359368
/**
360369
* Generate a random ID for this span. Must be unique per trace,
361370
* but does not need to be globally unique.

0 commit comments

Comments
 (0)