Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the UNIX timestamp from UUID version 1

In our Java application we are trying to get the UNIX time from the UUID version 1. But it's not giving the correct date time values.

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

Can someone please help?

like image 853
Thiyanesh Avatar asked Oct 25 '12 14:10

Thiyanesh


People also ask

Does UUID contain timestamp?

The timestamp value associated with this UUID. 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.

What is UUID timestamp?

UUID version 1 is based on the current timestamp, measured in units of 100 nanoseconds from October 15, 1582, concatenated with the MAC address of the device where the UUID is created. If privacy is a concern, UUID version 1 can alternatively be generated with a random 48-bit number instead of the MAC address.

How Unix timestamp is calculated?

The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the unix time stamp is merely the number of seconds between a particular date and the Unix Epoch.

What can I do with a UUID?

Universally Unique IDentifiers, also known as UUIDs or GUIDs, are 128-bit numbers used to uniquely identify information in computer systems. UUIDs can be used to refer a wide variety of elements (documents, objects, sessions, tokens, entities, and so on). They can also be used as database keys.


2 Answers

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
like image 64
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet


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)

like image 32
user3324777 Avatar answered Sep 28 '22 08:09

user3324777