2.0 KiB
2.0 KiB
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
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)"