get the unix timestamp from type 1 uuid

冷暖自知 提交于 2019-12-19 09:25:31

问题


In our java application we are trying to get the unix time from the type 1 uuid. But its not giving the correct date time values.

long time = uuid.timestamp();
time = time / 10000L; // Dividing by 10^4 as its in 100 nanoseconds precision 
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
c.getTime();

Can some one please help ?

Edit: Fixed the divisor(10^4)


回答1:


From the docs for timestamp():

The resulting timestamp is measured in 100-nanosecond units since midnight, October 15, 1582 UTC.

So you need to offset it from that. For example:

Calendar uuidEpoch = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
uuidEpoch.clear();
uuidEpoch.set(1582, 9, 15, 0, 0, 0); // 9 = October
long epochMillis = uuidEpoch.getTime().getTime();

long time = (uuid.timestamp() / 10000L) + epochMillis;
// Rest of code as before



回答2:


If you using datastax driver, it's:

UUIDs.unixTimestamp(uuid)

http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/utils/UUIDs.html#unixTimestamp(java.util.UUID)




回答3:


In my case, the following code worked.

    final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;
    UUID uuid = UUID.fromString("6470d760-d93d-11e9-8b32-858313a776ba");
    long  time = (uuid.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10000;
    // Rest of code as before



回答4:


In the case someone else needs it:

long milliseconds = UuidUtil.extractUnixMilliseconds(uuid);

https://github.com/f4b6a3/uuid-creator



来源:https://stackoverflow.com/questions/13070674/get-the-unix-timestamp-from-type-1-uuid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!