Search code examples
javauuidunix-timestamp

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?


Solution

  • 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