Skip to content

Commit 3eb765c

Browse files
authored
Fix UUIDv6 negative timestamps near Unix Epoch (#37)
1 parent 3ba6c93 commit 3eb765c

2 files changed

Lines changed: 14 additions & 3 deletions

File tree

src/UUID.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,13 @@ public static function getTime(string $uuid): ?string
260260
$timehex = '0' . substr($uuid, 0, 12) . substr($uuid, 13, 3);
261261
$retval = null;
262262
if ($version === 6) {
263-
$retval = strval(hexdec($timehex) - self::TIME_OFFSET_INT);
264-
$retval = substr_replace(str_pad($retval, 8, '0', \STR_PAD_LEFT), '.', -7, 0);
263+
$retval = '';
264+
$ts = hexdec($timehex) - self::TIME_OFFSET_INT;
265+
if ($ts < 0) {
266+
$retval = '-';
267+
$ts = abs($ts);
268+
}
269+
$retval .= substr_replace(str_pad(strval($ts), 8, '0', \STR_PAD_LEFT), '.', -7, 0);
265270
} elseif ($version === 7) {
266271
$unixts = hexdec(substr($timehex, 0, 10));
267272
$subsec = str_pad(strval(self::decodeSubsec(hexdec(substr($timehex, 10)))), 7, '0', \STR_PAD_LEFT);

tests/UuidTest.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,13 @@ public function testGetTimeNull()
215215

216216
public function testGetTimeNearEpoch()
217217
{
218-
$uuid6_time = UUID::getTime('1b21dd21-3814-6001-76fa-54fb559c5fcd');
218+
$uuid6_time = UUID::getTime('1b21dd21-3814-6001-b6fa-54fb559c5fcd');
219219
$this->assertSame($uuid6_time, '0.0000001');
220220
}
221+
222+
public function testGetTimeNegativeNearEpoch()
223+
{
224+
$uuid6_time = UUID::getTime('1b21dd21-3813-6fff-b678-1556dde9b80e');
225+
$this->assertSame($uuid6_time, '-0.0000001');
226+
}
221227
}

0 commit comments

Comments
 (0)