From 8a187711baf7bc38fb6cd5e441a7e41b33695388 Mon Sep 17 00:00:00 2001 From: cc Date: Mon, 3 Mar 2025 15:21:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20UUID.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UUID.md | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 UUID.md diff --git a/UUID.md b/UUID.md new file mode 100644 index 0000000..1007e99 --- /dev/null +++ b/UUID.md @@ -0,0 +1,65 @@ +UUID Note + + +1.github - uuidv7: A JavaScript implementation of UUID version 7 + +https://github.com/LiosK/uuidv7 +https://unpkg.com/uuidv7@1.0.2/dist/index.js + +2.sql function: Implementing V7 UUID in Postgres - How to implement v7 UUID in postgres with using SQL + +https://priver.dev/blog/postgres/implementing-v7-uuid-in-postgres/#:~:text=We%20use%20clock_timestamp%20to%20obtain%20the%20current%20time%2C,millisecond%20timestamp%20to%20a%20byte%20sequence%20using%20int8send. + +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; + +create or replace function uuid_generate_v7() +returns uuid +as $$ +select encode( + set_bit( + set_bit( + overlay(uuid_send(gen_random_uuid()) + placing substring(int8send(floor(extract(epoch from clock_timestamp()) * 1000)::bigint) from 3) + from 1 for 6 + ), + 52, 1 + ), + 53, 1 + ), + 'hex')::uuid; +$$ +language SQL +volatile; + + +3.Extract Timestamp from UUID v7 using Javascript + +https://park.is/blog_posts/20240803_extracting_timestamp_from_uuid_v7/ + +// extract Unix timestamp from a UUID v7 value without an external library + +在没有外部库的情况下从 UUID v7 值中提取 Unix 时间戳 +function extractTimestampFromUUIDv7(uuid: string): Date { + // split the UUID into its components + const parts = uuid.split("-"); + + // the second part of the UUID contains the high bits of the timestamp (48 bits in total) + const highBitsHex = parts[0] + parts[1].slice(0, 4); + + // convert the high bits from hex to decimal + // the UUID v7 timestamp is the number of milliseconds since Unix epoch (January 1, 1970) + const timestampInMilliseconds = parseInt(highBitsHex, 16); + + // convert the timestamp to a Date object + const date = new Date(timestampInMilliseconds); + + return date; +} + +// sample usage: +const uuid = "01911825-7f8f-74c9-85bc-55b034e2af75"; +const timestamp = extractTimestampFromUUIDv7(uuid); + +// check output +console.log(timestamp); +// prints "Sat Aug 03 2024 07:09:56 GMT-0500 (Central Daylight Time)" \ No newline at end of file