How do I extract a date from a UUID using Java? [closed]

时间秒杀一切 提交于 2019-12-03 01:58:55

The javadoc for UUID says the following about the timestamp field:

The 60 bit timestamp value is constructed from the time_low, time_mid, and time_hi fields of this UUID. The resulting timestamp is measured in 100-nanosecond units since midnight, October 15, 1582 UTC.

(emphasis mine)

The Java timestamp is in milliseconds since 1970-01-01. In order to get a meaningful date from a UUID, you'll need to do two things: convert from 100ns to 1ms precision (divide by 10000) and rebase from 1582-10-15 to 1970-01-01, which you can do by adding a constant value.

WolframAlpha tells us that 1582-10-15 corresponds to a UNIX timestamp of -12219292800, so to get the correct date, you must add 12219292800 to the number of milliseconds you got after dividing by 10000.

As a side note:

The timestamp value is only meaningful in a time-based UUID, which has version type 1. If this UUID is not a time-based UUID then this method throws UnsupportedOperationException.

...so make sure your code either only ever encounters Type 1 UUID's, or can handle that they don't have a timestamp.

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