Created
May 8, 2023 12:30
-
-
Save robinpokorny/3e1ef5eebce096824d3c2054202e4217 to your computer and use it in GitHub Desktop.
Validate UUIDv7 and parse the timestamp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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