daegalus / dart-uuid

Generate RFC9562(v1,v4,v5,v6,v7,v8) UUIDs
MIT License
356 stars 77 forks source link

How to get a Dart DateTime from a uuid.v1() ? #70

Closed jdavies closed 3 years ago

jdavies commented 3 years ago

Given the nature of the v1 uuid, I'd like to be able to easily convert the uuid into a Dart DateTime object. How would I do that? Thanks in advance!

daegalus commented 3 years ago

It won't be super accurate but the first 16 hex digits are the time.

First 8 hex digits are time_low The following 4 digits are time_mid Then the following 4 are time high and the version. So it's always 1xxx for UUIDv1. I think in most cases you can drop that 1 and get the time. But if that doesn't work, keep the one. I forget if we lose some time data or not.

To reconstruct time you need to rearrange them to be time_high, time_mid, time_low and then decode it to a byte array, then convert the byte array to a long/int.

That will be the timestamp, which you can use in datetime.

The experimental/draft UUIDv6 in the future will not mess with the time stamp so it can be easier to decode the time from that.

I hope that helped.

You can look at the code for V1 and do it in reverse for the time stuff. You will need to get comfortable with bitshifts and integer manipulation