LiosK / uuidv7

A JavaScript implementation of UUID version 7
Apache License 2.0
177 stars 3 forks source link

How to extract the time from uuid v7? #1

Closed lucgagan closed 1 year ago

lucgagan commented 1 year ago

I would like to add it to https://ray.run/tools/uuid-validator

The idea would be to extract timestamp in addition to recognizing the version

LiosK commented 1 year ago

Currently, this library doesn't provide APIs to inspect the internals of a UUID because the draft RFC doesn't strongly recommend that, but the library does provide the way to access to the underlying byte array representation. So perhaps the quickest way to extract the timestamp is:

import { uuidv7obj } from "uuidv7";

const uuidBytes = uuidv7obj().bytes;
const timestamp = uuidBytes.slice(0, 6).reduce((acc, e) => acc * 256 + e, 0);

console.log(timestamp, new Date(timestamp));
lucgagan commented 1 year ago

Thank you!

lucgagan commented 1 year ago

I just tried using this and realized that I cannot input a UUID.

I already have a UUID and I need to extract bytes from it.

Would you consider making that possible? @LiosK

lucgagan commented 1 year ago

Here is how I did, in case anyone else stumbles upon this.

const uuidToBytes = (uuid: string): number[] => {
  const bytes: number[] = [];

  uuid.replaceAll(/[\dA-Fa-f]{2}/gu, (hex) => {
    bytes.push(Number.parseInt(hex, 16));
    return hex;
  });

  return bytes;
};

const extractV7Timestamp = (uuid: string): number => {
  const bytes = uuidToBytes(uuid);

  return bytes
    .slice(0, 6)
    .reduce((accumulator, entry) => accumulator * 256 + entry, 0);
};
LiosK commented 1 year ago

With regex, it would be much easier:

import { uuidv7 } from "uuidv7";

const uuidString = uuidv7();

const m = uuidString.match(
  /^([0-9a-f]{8})-([0-9a-f]{4})-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
);

if (m) {
  const timestamp = parseInt(m.slice(1, 3).join(""), 16);
  console.log(timestamp, new Date(timestamp));
} else {
  throw new SyntaxError("could not parse a UUIDv7 string");
}
IlyaSemenov commented 5 months ago

@LiosK what if the library exported a function to convert uuidv7 string to a Date object? This seems to be a pure and tree shakeable function, so this will be 100% backwards compatible with zero burden for existing installs.