Created
April 26, 2023 10:40
-
-
Save robinpokorny/544c18e27d39573121c94c9419f7c498 to your computer and use it in GitHub Desktop.
Convert UUID v4 to v7 in JavaScript (or generate one)
This file contains 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 RFC4122bis C.6 | |
// https://ietf-wg-uuidrev.github.io/rfc4122bis/draft-00/draft-ietf-uuidrev-rfc4122bis.html#appendix-C.6 | |
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