Core\Uuid::v7
Creates a new UUID that starts with the current time, such as 0190d1e6-8e3c-7c2a-9a4b-1f2e3d4c5b6a. The first twelve digits are the number of milliseconds since 1 January 1970. Most of the other digits are random, so two calls never give the same UUID in practice.
Because the time comes first, a UUID created later sorts after one created earlier. This makes it a good key for a database table: new rows are added at the end of the index. Two UUIDs created in the same millisecond sort in a random order.
Anybody who has the UUID can read the time it was created. For an ID that other people see, use Core\Uuid::v4 instead.
The examples below show the parts of a new UUID that never change, check that a newer UUID sorts after an older one, and read the time a UUID was created.
Return value
Returns Core\Uuid. A new Uuid. It sorts after every UUID created in an earlier millisecond. Two UUIDs created in the same millisecond sort in a random order. Anybody who has the UUID can read the time it was created, so use Core\Uuid::v4 for an ID that other people see. If the computer's clock is before 1970, the time part is zero.
Examples
Create a time ordered id
<?nvs// Shows how to create a new UUID that starts with the current time.
// `Core\Uuid::v7` creates a new UUID. Its digits are different on every run.string $id = Core\Uuid::v7()->toString();
// The text is always 36 characters long. This prints 36.echo Core\Str::length($id), "\n";
// The third group always starts with the version of the UUID. This prints 7.echo Core\Str::slice($id, 14, 1), "\n";367A newer id sorts later
<?nvs// Shows that a UUID created later sorts after one created earlier.
// The program waits two milliseconds between the two UUIDs.string $older = Core\Uuid::v7()->toString();Core\Time::sleep(Core\Time\Duration::milliseconds(2));string $newer = Core\Uuid::v7()->toString();
// `Core\Str::compare` returns a number greater than 0 when the first text sorts later.// The newer UUID sorts later. This prints yes.echo Core\Str::compare($newer, $older) > 0 ? 'yes' : 'no', "\n";yesRead when a row was created
<?nvs// Shows how to read the time a row was created from its key.
class Key{ // The first 12 hex digits are the time in milliseconds. A hyphen is after digit 8. public static function createdAt(Core\Uuid $key): int { string $text = $key->toString(); string $digits = Core\Str::slice($text, 0, 8) . Core\Str::slice($text, 9, 4); return Core\Math::fromBase($digits, 16); }}
// A new row gets a new key.Core\Uuid $key = Core\Uuid::v7();
// The time in the key is the current time, so the difference is less than one second.// This prints created just now.int $age = Core\Time::now()->toEpochMillis() - Key::createdAt($key);echo $age >= 0 && $age < 1000 ? 'created just now' : 'created earlier', "\n";created just now