Last active
June 17, 2024 05:52
-
-
Save robinpokorny/544c18e27d39573121c94c9419f7c498 to your computer and use it in GitHub Desktop.
Convert UUIDv4 to UUIDv7 in JavaScript (or generate one) [RFC 9562]
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 uuid4to7 = (uuid, now = Date.now()) => { | |
const ts = now.toString(16).padStart(12, `0`) | |
return `${ts.slice(0, 8)}-${ts.slice(8)}-7${uuid.slice(15)}` | |
} | |
// generate new UUIDv7 | |
uuid4to7(crypto.randomUUID()) | |
// Conforms to example in the spec RFC9562 A.6 | |
// https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value | |
uuid4to7( | |
`6ed0cbe6-d1fb-4cc3-98c4-dc0c0c07398f`, | |
Date.parse(`2022-02-22T14:22:22-05:00`) | |
) | |
// -> `017f22e2-79b0-7cc3-98c4-dc0c0c07398f` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment