Extract date time from UUID V7
yashh opened this issue ยท 7 comments
Is there a way to extract date time from the UUID v7 generator?
@yashh It is generally discouraged to do so, e.g. https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-opacity
That being said, since the time stamp is defined as 48 bits (cf. https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#name-uuid-version-7), you can extract it with:
long timestamp = uuid.getMostSignificantBits() >>> (Long.SIZE - 48);
Thank you @pw-lehre . My only motive was to make sure the library is taking the current timestamp and which timezone. Thank you for pointer.
@yashh FWTW, timezone is not relevant; timestamps do not use or have it (generally it's offset from UTC but no timezone info is included).
@cowtowncoder Yup. I was using https://github.com/stevesimmons/uuid7 library to verify that timestamp and all checks out. But there is something wrong with that library. The timestamp its generating is around year 1983. I tried https://github.com/oittaa/uuid6-python and everything checks out.
Some implementations are based on old drafts. That's why https://github.com/stevesimmons/uuid7 is different.
In 2021, UUIDv7 reserved 36 bits for seconds (not milliseconds). To extract the timestamp from this particular implementation, you must extract the initial 36 bits.
UUID uuid = UUID.fromString("061cb26a-54b8-7a52-8000-2124e7041024");
long seconds = uuid.getMostSignificantBits() >>> (Long.SIZE - 36);
Instant instant = Instant.ofEpochSecond(seconds);
System.out.println(instant); // prints 2021-12-28T15:00:53Z
Makes sense. Thank you @fabiolimace
Good point: timestamps used are indeed different: original UUID versions (v1 - v4) used higher-granularity ones with 100 ns resolution -- these take lots of space (bits). So v7 trades in smaller size for lower granularity.