Skip to content

Instantly share code, notes, and snippets.

@robinpokorny
Created May 8, 2023 12:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinpokorny/3e1ef5eebce096824d3c2054202e4217 to your computer and use it in GitHub Desktop.
Save robinpokorny/3e1ef5eebce096824d3c2054202e4217 to your computer and use it in GitHub Desktop.
Validate UUIDv7 and parse the timestamp
const uuid7Re = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const parseUuid7Date = (uuid) => {
if (typeof uuid !== `string` || !uuid7Re.test(uuid)) {
throw new TypeError(`Expected UUIDv7. Received: ${String(uuid)} (${typeof uuid})`)
}
const timestampHex = uuid.slice(0, 13).replace(`-`, ``)
const timestamp = Number.parseInt(timestampHex, 16)
return new Date(timestamp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment